Reputation: 115
I am brand new to Python and am trying to build a text based game. The first question is "How old are you?"
How can I use if/else statements to print a certain message when the user doesn't input his age.
for instance if the user inputs a character instead of a letter I want to print "please enter a digit, not characters" or if the user inputs a digit smaller than 12 I want to print "You are not old enough" and if the user inputs a digit greater or equal to 12 I want to say "Welcome"
I have written some code to try and do this myself and spent about 4 hours on it but can't figure it out.
This is my block of code:
input_age = raw_input("What is your age, " + input_name + "? ")
if len(input_age) == 0:
print("You didn't enter anything")
elif input_age < 12 and input_age.isdigit():
print("Sorry, you are not old enogh to play")
elif input_age >= 12 and input_age.isdigit():
print ("Welcome")
else:
print("You entered a character or characters instead of a digit or digits")
For some reason the elif on line 4 gets skipped or something because even if i enter 4 as my age it still carries on and prints "Welcome" instead of "You are not old enough"
Upvotes: 0
Views: 189
Reputation: 71570
@roganjosh is right, raw_input
returns a string, so you have to do the below:
input_age = raw_input("What is your age, " + input_name + "? ")
if not input_age:
print("You didn't enter anything")
elif input_age.isdigit():
if int(input_age) < 12 :
print("Sorry, you are not old enogh to play")
elif int(input_age) >= 12:
print ("Welcome")
if not input_age.isdigit():
print("You entered a character or characters instead of a digit or digits")
Upvotes: 1