I was just messing around with python command prompt when I discovered something, that I personally didn't know of.
This is one mystery that I'm trying to solve:
num = int(5) / 2
num == float # False
I found it weird that it didn't return True
. So i tried with other operators.
num == int # False
num == str # False
they all return False, but when i check which type
it is. It gives me this.
type(num) # Float
Shouldn't it have returned True
when i compared it to the float
operator?
Does anyone know why this is?
Your num
contains the value 2.5
, it doesn't hold the type float
so num == float
can't be true
What can be true is
comparing to the value 2.5
print(num == 2.5) # true
comparing num's type to the float
type
print(type(num) == float) # true
checking if the type of num
is float
print(isinstance(num, float)) # true
You're comparing an object(of type float
) with a class( float
in this case). To get True, you should compare the type of num
with float
:
type(num) == float
You can also do:
isinstance(num, float)
which is better according to PEP8(Coding style convention for python).
Both will return True
.
Actually num = int(5) / 2
gives you in result 2.5 not float, when you are checking the type of variable you have to write something like this
type(num) == float
not num == float
because num is 2.5 not float
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.