Python重启While循环运行异常,IDLE直接返回>>>问题求助
问题原因
你的代码逻辑存在两个核心错误导致无法重启轮询:
- 重启轮询的
polling_active = True逻辑放在了打印结果的for循环内,且原轮询while循环已经执行结束,没有外层循环触发重新进入while polling_active的逻辑 continue关键字只能跳出当前所在层循环的本次迭代,你写在for循环里的continue只会作用于for循环,不会回到最外层的轮询while循环
修正后可正常重启的代码
while True: 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}.") # 重启逻辑移到for循环外,由外层无限循环控制是否重新启动轮询 restart = input("\nWould you like to start a new poll? (yes/no) ") if restart == 'no': print("Thank you, have a good day!") break
改动说明
- 新增一层外层无限
while True循环,包裹整个轮询+结果打印流程,用来控制是否重启整个轮询任务 - 将是否重启轮询的输入判断逻辑从
for循环内移到结果打印完成之后,避免每打印一条轮询结果就触发一次重启询问 - 用
break关键字代替原逻辑中的continue,用户选择不重启时直接终止外层无限循环,程序正常退出
内容的提问来源于stack exchange,提问作者bigorangeduck
相关产品推荐
相关产品推荐

