Reputation: 21
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
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
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