Reputation: 167
No mather what input I give I get the output "I think you're to old to go on an adventure. Your adventure ends here." Like if I input 17 I get "I think you're to old to go on an adventure. Your adventure ends here." and if I input 18-59 I get "I think you're to old to go on an adventure. Your adventure ends here."
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
Upvotes: 0
Views: 139
Reputation: 6935
The problem is that raw_input
always returns a string object, and those don't really compare to int
types. You need to do some type conversion.
If you want to use isdigit
to test if the input is a number, then you should proceed this way:
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif int(age) < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif int(age) >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
However, you can simplify the code a little by converting to an integer right away, and just catching the exception if it's an invalid string:
while True:
try:
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
if age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
except ValueError:
print "\n Please, put only in numbers!"
time.sleep(3)
Upvotes: 1
Reputation: 117856
You need to compare your input as an int
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
Otherwise you are comparing a str
to an int
. See the following example
>>> 5 < 10
True
>>> type(5)
<type 'int'>
>>> '5' < 10
False
>>> type('5')
<type 'str'>
In Python 2.x, comparing values of different types generally ignores the values and compares the types instead. Because str >= int
, any string is >=
any integer. In Python 3.x you get a TypeError
instead of silently doing something confusing and hard to debug.
Upvotes: 3