Python 在两个级别输入有效值之前,如何继续请求输入?
我正在做一个问题,其中我为拼字游戏创建了各种功能。首先,我想让用户输入Python 在两个级别输入有效值之前,如何继续请求输入?,python,Python,我正在做一个问题,其中我为拼字游戏创建了各种功能。首先,我想让用户输入n或r或e开始新游戏/重放最后一手牌/结束游戏 游戏开始后,我想让用户输入u或c,让用户或计算机进行游戏 我陷入了问题的最后一部分 我的代码: hand = None while True: choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ').lower() if choice =
n
或r
或e
开始新游戏/重放最后一手牌/结束游戏
游戏开始后,我想让用户输入u
或c
,让用户或计算机进行游戏
我陷入了问题的最后一部分
我的代码:
hand = None
while True:
choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ').lower()
if choice == 'e':
break
elif choice=='n':
Your_choice = input('Enter u to play yourself or c to let the computer play: ')
if Your_choice == 'u':
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
elif Your_choice == 'c':
hand = dealHand(HAND_SIZE)
compPlayHand(hand, wordList,HAND_SIZE)
else:
print('Invalid command.')
elif choice == 'r':
if hand == None:
print('You have not played a hand yet. Please play a new hand first!')
else:
Your_choice = input('Enter u to play yourself or c to let the computer play: ')
if Your_choice == 'u':
if hand != None:
playHand(hand.copy(), wordList, HAND_SIZE)
else:
print('You have not played a hand yet. Please play a new hand first!')
elif Your_choice == 'c':
if hand != None:
compPlayHand(hand.copy(), wordList, HAND_SIZE)
else:
print('You have not played a hand yet. Please play a new hand first!')
else:
print('Invalid command.')
else:
print('Invalid command.')
如果内部循环的选择不是u或c,它应该反复通知并询问,直到u或c成为输入。但在第一次尝试之后,它就从这个循环中走出来了
理想输出:
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Enter u to have yourself play, c to have the computer play: x
Invalid command.
Enter u to have yourself play, c to have the computer play: y
Invalid command.
Enter u to have yourself play, c to have the computer play: z
Invalid command.
Enter u to have yourself play, c to have the computer play: k
Invalid command.
我的输出:
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Enter u to play yourself or c to let the computer play: x
Invalid command.
Enter n to deal a new hand, r to replay the last hand, or e to end game: y
Invalid command.
问题是,当用户在第二级输入无效命令时,我的代码开始询问第一级的问题。您需要的是python中的break语句,它停止最内部的循环,这样您可以执行以下操作:
while:
Your_choice = input('Enter u to play yourself or c to let the computer play: ')
if Your_choice in ["u", "c"]:
# Do stuff
break
else:
print("Incorrect option")
文档中的更多信息:
在编写代码之前,绘制一个您试图完成的任务的流程图有助于您在脑海中勾勒出代码需要的样子。而且|