繁体   English   中英

在 Python 中重新启动 While 循环的问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM