![](/img/trans.png)
[英]Is there any way in python to repeat a while or for loop by asking the user to do so at the end of the loop?
[英]while loop, asking user if he wants to repeat the program problem
所以我有這個 while 循環,它詢問用戶是否要重復該程序。 一切正常,但我正在嘗試並發現在用戶重復該程序后,當第二次詢問他/她是否要重復時,我選擇否。 但是程序仍然重復,盡管它打印出程序正在關閉,我該如何解決這個問題?
編輯:我已經通過更改中斷和返回並在 main() 之后添加返回來修復它
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
這是因為 main() function 被遞歸調用並且 endFlag 是局部變量。
所以當你第一次輸入 'y' 時,然后從第一個 main() function 遞歸調用另一個 main()。
在你放置結束第二個 main() 的 'n' 並返回到第一個 main 之后,它仍然在一個循環中,endFlag(局部變量)值為 false。
所以,需要改變,
endFlag 變量作為全局變量(即在 main function 之外定義)
要么,
一些程序退出 function 代替中斷
問題是你在這里進行遞歸,即你在main()
main()
並試圖按照你所做的方式突破它是行不通的(好吧,你知道的:) ) 其次 - 你不需要在第一個循環中有一個永遠的循環,你可以用一個簡單的循環和中斷來完成。 這里是:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
這是你應該做的:(順便說一句,這是一段示例代碼)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(我不確定我是否正確放置了縮進)您可以將這個概念應用到您的代碼中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.