我不明白尝试,除了然后继续

问题描述 投票:0回答:1

我正在创建一个 .py 游戏,我需要用户输入仅包含 1,2 或 3。我希望菜单在开始时询问用户一次输入这三个数字之一,如果用户输入任何其他内容,它将重复该问题并向用户发出通知。

目前我有这个...

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

我对编码很陌生,所以要友善啊哈哈。抱歉,如果这是一个明显的修复,或者如果这篇文章根本没有意义

python try-catch
1个回答
0
投票

您不需要

try-catch
来实现所需的行为。
if-else
就够了:

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 game\n''')
    if menu_input in ['1', '2', '3']:
        print(f'Menu number: {menu_input}')
        break
    else:
        print('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
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
© www.soinside.com 2019 - 2024. All rights reserved.