Reputation: 83
My question is, why are these expressions False?
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num = raw_input("Choose a number: ")
Choose a number: 5
>>> print num
5
>>> print ( num < 18 )
False
>>> print ( num == 5 )
False
Because if i try this:
>>> print ( num > 0 )
True
The expression works fine.
Upvotes: 4
Views: 369
Reputation: 370092
num
is a string. You can't meaningfully compare a string to an integer and a string is never equal to an integer (so == returns false and <
and >
return whatever they want). The reason that <
and >
don't throw an error (before python 3) when you compare strings and integers is to be able to sort heterogeneous lists.
Upvotes: 2
Reputation: 181705
The variable num
does not actually contain the number 5
; it contains the string "5"
. Because Python is strongly typed, 5 == "5"
is False
. Try converting it to an integer first:
>>> print (int(num) < 18)
True
Upvotes: 3
Reputation: 881487
This statement:
num = raw_input("Choose a number: ")
makes num
a string, not a number, despite its misleading name. It so happens that Python 2 lets you compare strings with numbers, and in your version considers all strings larger than all numbers (the contents of the string play no role).
Use num = int(num)
to make an integer (and be sure to use a try/except to catch possible errors when the user has typed something other than a number!) before you start comparing.
(In Python 3, the function's name changes from raw_input
to input
, and it still returns strings; however in Python 3 comparing a string with a number is considered an error, so you would get an exception rather than True
or False
in each of your comparison attempts).
Upvotes: 9
Reputation: 49156
Try num = float(raw_input("Choose..."))
You're evaluating a string in your boolean expressions.
Upvotes: 1