MadMax
MadMax

Reputation: 21

Python 2.7 raw_input

age = raw_input("How old are you? ")
print(age)
if age>= 18:
    print("You can vote!")

I am running this code on python 2.7. I was expecting to get an error but I didn't. I thought variable age would have a string value like '21'. This way, when I compare age>= 18, it would flag me saying you cannot compare string and int. But it did not. It ran fine.

Upvotes: 2

Views: 5772

Answers (2)

C. Carley
C. Carley

Reputation: 133

In Python 2.X you can compare strings with integers but strings will always be considered greater than integers. If you want to capture user input as an integer just use:

age = input("number here: ");

Hope this helps!

Upvotes: 1

blurb
blurb

Reputation: 610

From a similar question, here:

You are indeed right in that you're comparing a string and an int. However, it will not flag you saying that you cannot do that. With types that are not the same, it will simply compare the type of the variables (in this case int, and str). In python 3.x, it makes it so that this comparison is impossible. By chance, in python 2.x the comparison would go ("int" < "string") which is what we're seeing here.

Upvotes: 0

Related Questions