我正在制作一個代碼,它將用戶輸入從字母更改為數字。我用每個字母作為鍵和相應的數字值制作了一個字典。
為了使代碼自動運行(我不必每次都運行),我使用了一個 while 回圈。
start_over = input("Please Enter (Y) to start and (N) to stop: ").lower()
While start_over == "y" : # First While Loop
(the alphabet changer code here)
start_over = input("Enter (Y) to continue and (N) to stop: ").lower()
While start_over != "y" and start_over != "n" : # Second while loop
start_over = input("Enter (Y) to continue and (N): ")
While start_over == "n": #Third While Loop
print("Thanks for using the code")
break
現在的問題是當我輸入 Y 時,第一個 while 回圈運行并且它正常作業。如果我輸入 N,則運行第三個 while 回圈并且代碼會按需要中斷。但是當我放除 Y 和 N 之外的任何東西時,第二個 while 回圈運行并要求我放其他任何東西。當我將 N 放在第二個 while 回圈中時,代碼會根據需要中斷。但是當我在第二個 while 回圈中輸入 Y 時,代碼會中斷而不是運行第一個 while 回圈。為什么會發生這種情況我不知道。
uj5u.com熱心網友回復:
問題是當您的代碼進入第二個while回圈和用戶輸入時start_over = 'y'。它不會移動到您的第一個while回圈,因為它位于上方。為避免這種情況,您可以將第二個while放入函式中:
def start(start_over):
while start_over != "y" and start_over != "n" :
start_over = input("Enter (Y) to continue and (N): ")
return start_over
start_over = input("Please Enter (Y) to start and (N) to stop: ").lower()
if start_over != "y" and start_over != "n" :
start_over = start(start_over)
while start_over == "y" :
start_over = input("Enter (Y) to continue and (N) to stop: ").lower()
if start_over != "y" and start_over != "n" :
start_over = start(start_over)
while start_over == "n": #Third While Loop
print("Thanks for using the code")
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469360.html
標籤:python-3.x while循环 覆盖
