[英]Issues With Restarting a While Loop In Python
我正在嘗試重新啟動While循環,但遇到了問題。 我嘗試了幾種方式來格式化代碼,IDLE 總是返回“>>>”
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
response = input("\nWould you like to start a new poll? (yes/no) ")
if response == 'yes':
polling_active = True
continue
if response == 'no':
print("Thank you, have a good day!")
continue
將您的 while 循環放在一個單獨的函數中,如下所示:
def poll():
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
polling_active = False
然后,不要在最后調用 continue,只需運行此函數即可。
Python 是一種解釋器語言。 代碼從上到下運行。 一旦它退出你的 while 循環。 它無法返回。 只需使用上述答案中提到的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.