Why is this a boolean expression in python False?

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 great.

+4
source share
4 answers

This statement:

 num = raw_input("Choose a number: ") 

does num a string , not a number, despite its misleading name. It so happened that Python 2 allows you to compare strings with numbers, and in your version all strings larger than all numbers are taken into account (the contents of the string do not matter).

Use num = int(num) to make an integer (and be sure to use try / except to catch possible errors when the user typed something other than the number!) Before starting the comparison.

(In Python 3, the function 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 should get an exception, not True or False in each of your comparison attempts).

+9
source

The variable num does not actually contain the number 5 ; it contains the string "5" . Since Python is strongly typed, 5 == "5" is False . Try converting it to an integer first:

 >>> print (int(num) < 18) True 
+3
source

num is a string. You cannot significantly compare a string with an integer, and the string will never be equal to an integer (therefore == returns false and < and > returns whatever it wants). The reason that < and > does not throw an error (before python 3) when comparing strings and integers should be able to sort heterogeneous lists.

+2
source

Try num = float(raw_input("Choose..."))

You evaluate the string in your boolean expressions.

+1
source

Source: https://habr.com/ru/post/1306615/


All Articles