Tags
python
Asked 3 years ago
5 Aug 2021
Views 325
Freeman

Freeman posted

How do you use GT in Python ?

How do you use GT in Python ?
Mitul Dabhi

Mitul Dabhi
answered Aug 9 '21 00:00

operator. gt() i s used to compare two-variable or values and give you true or false returns based on the values.
if suppose x and y passed to operator.gt(x,y):
suppose x is greater than y than it returns: True
suppose y is greater than x than it returns: False

gt() function come from operator module so you need to import operator before use of gt() function , otherwise you will get following error
NameError: name 'operator' is not defined

Example 1 :

import operator
x=2
y=1
print(operator.gt(x,y))


clearly, in the above example, x is greater than y so it will print True

Example 2 :

import operator
x=2
y=10
print(operator.gt(x,y))


clearly, in the above example, y is greater than x so it will print False
jagdish

jagdish
answered Aug 9 '21 00:00

instead of operator. gt() , use >(greater than sign) arithmetic operator from Python core, it short and sweet and easy to remember because all programming does have this

suppose x>y you are checking that if x is greater than y then it returns True, and if x is not greater than y then it returns False


print(2>1)

easy , isnt it ?
you don't need to import anything, just use > sign to check whether the first value is greater than the second or not .

> is very easy than operator. gt() , and short-handed and no extra code to import anything .


ching

ching
answered Aug 9 '21 00:00

Lets see how operator. gt() or < react with list


what happen if we pass two lists in operator. gt()

import operator
x=[10,10]
y=[1.10]
print(operator.gt(x,y))
print(x>y)


it will print True both of time,
operator.gt(x,y) = True
x>y=True

as you can see above i made two lists, x had higher values than y but operator. gt() and >(greater than the operator) only compare the first value of lists, not others
so above it prints True in any case where the first value of list , x is greater than the first value of y list

x=[10,0]
y=[1.10]
print(operator.gt(x,y))

so it still prints True because only compare the first value of two lists

what happens if we pass one parameter is an integer and the other is a list in the operator. gt() ?
Let's see, in the below code we passing one is an integer and the second is list


import operator
x=10
y=[1.10]
print(operator.gt(x,y))


it will show you the following error :
TypeError: '>' not supported between instances of 'int' and 'list'

Post Answer