Reputation: 13
I want the program to only allow the numbers 1-4 to be used as input and not any letters or numbers outside of that range. This is the code I have right now but it is not working:
# Get the user's choice.
choice = int(input("what would you like to do ? "))
# Validate the choice.
while choice < 1 or choice > 4:
try:
choice = int(raw_input("Enter a valid choice: "))
except ValueError:
print ("Please enter a numeric value.")
# return the user's choice.
return choice
Upvotes: 1
Views: 940
Reputation: 4035
Here is your solution
while True:
try:
choice = int(input("what would you like to do ? "))
except ValueError:
print ("Invalid choice.Valid choises are between 1-4.")
continue
if choice<1 or 4<choice:
print ("Invalid choice.Valid choises are between 1-4.")
continue
else:
print ("some codes will work on here..")
Upvotes: 1
Reputation: 19733
try like this:
def get_choice():
while True:
choice = raw_input("Enter a valid choice between 1 and 4: ")
if choice.isdigit():
if 1<= int(choice) <=4:
print choice
return choice
else:
print ("Please enter a numeric value.")
str.isdigit()
: check for if the string is digit or not, if digit return True else False
Upvotes: 0
Reputation: 898
You can try something like this:
def ask():
# Get the user's choice.
choice = raw_input("what would you like to do ? "))
return choice
#you can put this in while True infinite loop if you want it to ask again and again
choice = ask()
# Validate the choice.
if choice.isdigit():
if (choice > 0) and (choice < 5):
print choice
else:
print "Input must be between 1 and 4!"
else:
print "Input must be digit!"
Using isdigit() you check if string is digit. It returns True or False. Here's some doc:
https://docs.python.org/2/library/stdtypes.html#str.isdigit
I hope this helps and fits ur needs ;)
Upvotes: 0