[英]How can I continue asking for input until a valid value is entered at two levels?
我正在做一個問題,我為拼字游戲創建了各種功能。 首先,我想讓用戶輸入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")
文檔中的更多信息: https : //docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.