+ 3

[Python] Different types comparison

Why do comparisons of different types not produce an error? f.e.: if ("12" == 5): doSomething() Because of python is typed language I thought that you can't compare two different types. Correct me if I'm wrong. Thank ya

23rd Feb 2018, 11:12 PM
Rasťo Zlacký
4 ответов
+ 1
You can compare them, but they will return False. That's why the following would print "False" If "12" == 12: print("True") else: print("False")
24th Feb 2018, 1:20 AM
LordHill
LordHill - avatar
+ 1
I'd guess smaller or larger compares difference in numerical size where == and != compares wether or not something are the same thing of not, and that makes the difference
24th Feb 2018, 12:42 PM
Markus Kaleton
Markus Kaleton - avatar
0
Yes, it doesn't produce an error. But I was wandering why it doesn't produce an error. f.e. This code produces an error: if "12" <= 32: doSomething() But this code does not produce an error: if "12" == 32: doSomething() So why equivalence supports different types?
24th Feb 2018, 10:37 AM
Rasťo Zlacký
0
As Markus said.. it is a type error if your checking the value of a string.. comparing them is not a problem. is "12==12.. no, they aren't equals. is "12" > than something.. that is an error
24th Feb 2018, 2:54 PM
LordHill
LordHill - avatar