我現在遇到的問題是這個。由于原始代碼太長,無法寫在這里,我跳過了所有公告和 elif,else 回復1,2,3 項。當我在 line6:reply2 = input() 中輸入錯誤的輸入時,我想看到程式回傳到 line5:print(choice_2)。但是程式一直回傳給我 print(choice_1) 我該如何解決這個問題?任何幫助將不勝感激。
while True:
print(choice_1)
reply1 = input()
if reply1 in pos:
print(choice_2)
reply2 = input()
if reply2 in pos():
print(choice_3)
reply3 = input()
if reply3 in pos:
print('Nice choice.')
if reply1 and reply2 and reply2 in whole:
break
else:
print('Wrong input. Please type again.\n')
uj5u.com熱心網友回復:
可以改進代碼結構以減少嵌套,這樣做可以解決您的問題:
print(choice_1)
reply1 = input()
while reply1 not in pos:
print('Wrong input. Please type again.\n')
reply1 = input()
print(choice_2)
reply2 = input()
while reply2 not in pos:
print('Wrong input. Please type again.\n')
reply2 = input()
print(choice_3)
reply3 = input()
while reply3 not in pos:
print('Wrong input. Please type again.\n')
reply3 = input()
print('Nice choice.')
這應該可以解決您的直接問題,但您也可以將用戶輸入的請求也移動到輔助方法,并在 for 回圈中列印所有內容:
def seek_user_input(pos):
reply = input()
while reply not in pos:
print('Wrong input. Please type again.\n')
reply = input()
for choice in [choice1, choice2, choice3]:
print(choice)
seek_user_input(pos)
print('Nice choice.')
此代碼的結構使得添加更多問題供用戶查看變得更加容易。
通常,如果您的代碼具有例外大的嵌套深度,則可能有更好的撰寫方法。
uj5u.com熱心網友回復:
如果您實際上只想檢查輸入是在串列中還是在不同型別的物件中,您可以將 if 陳述句從 1 和 2 更改為 while 回圈。這將使您保持在同一階段,但除非該操作為真,否則不會取得進展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400834.html
