如何继续请求输入,直到在两个级别输入有效值为止



我正在做一个问题,我为拼字游戏创建了各种功能。首先,我想让用户输入nre来开始新游戏/重放最后一手牌/结束游戏。

一旦游戏开始,我想让用户输入uc,让用户或计算机玩。

我陷入了问题的最后一部分。

我的代码:

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")

文档中的更多信息:https://docs.python.org/3/tutorial/controlflow.html#break-和循环上的continue语句和else子句

最新更新