9 Antworten
+ 3
Ipang So is using 'is' better than using '=='? I can't think of a time they would produce different outcomes?
+ 3
Russ
Then I take that as a yes, when it comes to type comparison, in particular 👌
+ 3
'is' seems logical when there's really only one object, like with True, False, None etc.
So I'd go with 'is' for types as well.
(Or when you got to make sure that an object is really the very same object before you do something with it.)
(== logically is most fittingly used to check, if two *separate* objects have the same value.)
There might be different ways to achieve what you want to do depending on what *exactly* you want to do.
In some situations you can prevent that floats come into existence in the first place.
In division you could for example use //, after you checked 'if not x%y'.
So what's the purpose exactly?
+ 2
Something like this?
x = 4
y = 2.4
if type(x) == type(y):
print(x+y)
else:
print("Sorry, different types!")
#Sorry, different types!
+ 2
#Better:
A = input ("Enter first value : ")
B = input("Enter Second value : ")
If type(A) == type(B):
print(A+B)
else:
print("""The number types ( i.e.[integer,float,string]) are not the same.Please enter different values.""")
+ 2
Russ
A bit off, when comparing types, which operator is more appropriate? for example ...
Assume:
a, b = 5, 7
print(type(a) == type(b))
print(type(a) is type(b))
Gives the same result ...
+ 2
Ipang I'm sorry, I think I may have mis-explained myself.
There are certainly many times where 'is' will produce a different outcome to '==', but I wondered whether, specifically when comparing two types of object, they could produce different outcomes.
+ 1
Russ
In that case this means the two operators overlap each other's functionality or being redundant perhaps?
0
x = 5
y = 9.3
if type(x) == type (y):
print(x + y)
else:
print("Sorry, I can't do it!!!")