Reputation: 3
mySpeed = input("What is your speed? ")
if mySpeed < ("50"):
print ("safe")
Why does this print if the value is above 99?
Upvotes: 0
Views: 183
Reputation: 81
You can't evaluate a string as if it were an integer. Think of a string as the word "ten", whereas the integer is "10". You can't add the three letters t-e-n to an integer and result in a number. However, you can add "10+10", for example to result in "20". Your code should look like this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
NOTE: by using the int()
function to turn users' input into an integer, you are not in fact verifying what they input. If the user inputs a string, such as "ten", your code will return an error because "ten" cannot be converted into an integer.
My answer isn't best practice, but it will "work".
Upvotes: 0
Reputation: 17186
Because you are comparing two strings, not two integers. A string is a sequence and for a sequence comparison works as follows:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
So if you take a number large than '99'
, e.g. '100'
it will take the first character '1'
and compare it to '5'
(first character of '50'
). '1'
is smaller than '5'
in ascii ('1'==49
and '5'==53
). So this comparison will already terminate and the result will be that indeed '100'
is smaller than '50'
.
For the same reason '9'
is not smaller than '50'
:
In [1]: b'9'<b'50'
Out[1]: False
You should compare integers, as follows:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
Upvotes: 2
Reputation: 236094
Try this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
# same as before
Explanation: you should read a number and compare it against a number. Your code currently is reading a string and comparing it against another string, that's not going to give the results you expect.
Upvotes: 4
Reputation: 5289
mySpeed < ("50")
is checking a string. You need to be working with integers:
mySpeed = input("What is your speed? ")
if mySpeed < (50):
print ("safe")
Upvotes: 0
Reputation: 4343
"50" is a string, not a number ... try eliminating the " " ...
If mystring is a string, try a cast with the int-function - e.g. int(mystring)
Upvotes: 1