I don't understand try, except and continue
Question:
I am creating a .py game where I need to have user inputs that only consist of 1,2 or 3. I would like it so that the menu asks the user once at the beginning to enter one of these three numbers and if the user enters anything else it will repeat the question and raise a notice to the user.
Currently I have this…
while menuContinue:
try:
menuInput = input("""
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
""")
except:
break
if menuInput == "1":
results = gameMain(0,0)
elif menuInput == "2":
etc more irrelevant code
I’m quite new to coding so be nice ahah. sorry if its an obvious fix or if this post makes no sense at all
Answers:
You don’t need try-catch
to achieve desired behaviour. if-else
is enough:
while True:
menu_input = input('''Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the gamen''')
if menu_input in ['1', '2', '3']:
print(f'Menu number: {menu_input}')
break
else:
print('Incorrect menu number')
Output:
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
5
Incorrect menu number
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
2
Menu number: 2
I am creating a .py game where I need to have user inputs that only consist of 1,2 or 3. I would like it so that the menu asks the user once at the beginning to enter one of these three numbers and if the user enters anything else it will repeat the question and raise a notice to the user.
Currently I have this…
while menuContinue:
try:
menuInput = input("""
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
""")
except:
break
if menuInput == "1":
results = gameMain(0,0)
elif menuInput == "2":
etc more irrelevant code
I’m quite new to coding so be nice ahah. sorry if its an obvious fix or if this post makes no sense at all
You don’t need try-catch
to achieve desired behaviour. if-else
is enough:
while True:
menu_input = input('''Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the gamen''')
if menu_input in ['1', '2', '3']:
print(f'Menu number: {menu_input}')
break
else:
print('Incorrect menu number')
Output:
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
5
Incorrect menu number
Enter the number corresponding to what you would like to do,
1. Play the game
2. Learn the instructions of the game
3. Find the leaderboard of the game
2
Menu number: 2