Why Is This Python Function Not Working?
Keeps returning 'You are older than some hills' even if i input less than 30 age = raw_input('What age are you?') def old(n): if n >= 30: print 'You are older than some h
Solution 1:
Because you forgot to convert your input to a number, as it stands it is a string, and in Python 2 any string is always greater than any number.
Use int(raw_input("What age are you?"))
(Python 3 throws an error when you try to compare a string and a number, which is a good design decision.)
Solution 2:
As others have said, you need to convert the input to an integer. However, if the user inputs a letter, the program will throw an error. To make sure this doesn't happen, I would recommend getting the input using try and except, this can be done as follows:
age = raw_input("What age are you?")
try:
int(age)
except ValueError:
print('That is not a number')
Solution 3:
The raw_input()
function uses the input as strings, therefore, you should convert the input to int
type.
age = int(raw_input("What age are you?"))
defold(n):
if n >= 30:
print"You are older than some hills"else:
print"Youth"
old(age)
This will work.
Post a Comment for "Why Is This Python Function Not Working?"