Reputation: 423
I would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer. Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this? Maybe with while loop?
def get_main_menu_choice():
ask = True
while ask:
try:
number = int(input('Chose an option from menu: '))
while number not in range(1, 3):
number = int(input('Please pick a number from the list: '))
ask = False
except: # just catch the exceptions you know!
print('Enter a number from the list')
return number
Will be grateful for help.
Upvotes: 3
Views: 5323
Reputation: 11
def user_number():
# variable initial
number = 'Wrong'
range1 = range(0,10)
within_range = False
while number.isdigit() == False or within_range == False:
number = input("Please enter a number (0-10): ")
# Digit check
if number.isdigit() == False:
print("Sorry that is not a digit!")
# Range check
if number.isdigit() == True:
if int(number) in range1:
within_range = True
else:
within_range = False
return int(number)
print(user_number())
``
Upvotes: 1
Reputation: 5324
I would write it like this:
def get_main_menu_choice(prompt=None, start=1, end=3):
"""Returns a menu option.
Args:
prompt (str): the prompt to display to the user
start (int): the first menu item
end (int): the last menu item
Returns:
int: the menu option selected
"""
prompt = prompt or 'Chose an option from menu: '
ask = True
while ask is True:
number = input(prompt)
ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
return int(number)
Upvotes: 0
Reputation: 10759
I guess the most clean way of doing this would be to remove the double loops. But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what. I'd personally go for:
def get_main_menu_choice():
while True:
try:
number = int(input('Chose an option from menu: '))
if 0 < number < 3:
return number
except (ValueError, TypeError):
pass
Upvotes: 2
Reputation: 25789
If you need to do validation against non-numbers as well you'll have to add a few steps:
def get_main_menu_choice(choices):
while True:
try:
number = int(input('Chose an option from menu: '))
if number in choices:
return number
else:
raise ValueError
except (TypeError, ValueError):
print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))
Then you can reuse it for any menu by passing a list of valid choices, e.g. get_main_menu_choice([1, 2])
or get_main_menu_choice(list(range(1, 3)))
.
Upvotes: 0
Reputation: 8378
If your integer number is between 1 and 2 (or it is in range(1,3)) it already means it is a digit!
while not (number in range(1, 3)):
which I would simplify to:
while number < 1 or number > 2:
or
while not 0 < number < 3:
A simplified version of your code has try-except around the int(input())
only:
def get_main_menu_choice():
number = 0
while number not in range(1, 3):
try:
number = int(input('Please pick a number from the list: '))
except: # just catch the exceptions you know!
continue # or print a message such as print("Bad choice. Try again...")
return number
Upvotes: 0
Reputation: 11
see if this works
def get_main_menu_choice():
while True:
try:
number = int(input("choose an option from the menu: "))
if number not in range(1,3):
number = int(input("please pick a number from list: "))
except IndexError:
number = int(input("Enter a number from the list"))
return number
Upvotes: 0