Python中输入No时如何重启程序?(VS Code环境)
解决方法
你的问题出在两个核心点:
- 代码最后一行的
exit()会强制终止程序,不管前面的逻辑走到哪一步 - 输入"No"时没有让循环回到开头,反而继续执行后续代码,最终触发
exit()
关键调整方向
- 删掉末尾的
exit(),靠while True循环和continue/break控制流程 - 当用户输入"No"时(统一转成小写,兼容大小写输入),用
continue直接回到循环开头,重新启动输入流程 - 第二个产品确认错误时,同样用
continue重启整个程序 - 所有流程完成后,添加退出选项,用
break终止循环
修改后的完整代码
while True: product = input("Enter product name: ") price = float(input("What is the price of the product: ")) print(f'''You want to save towards purchasing {product.title()} which costs {price} dollars(Can)''') correct = input("Is this correct, Yes or No: ").lower() # 统一转小写,避免大小写识别问题 if correct == "no": print("Re-enter correct data") continue # 直接回到循环开头,重新输入 if correct == "yes": add_a_second_product = input("would you like to add a second product, Yes or No: ").lower() if add_a_second_product == "no": current_saved = float(input("How much money do you currently have saved: ")) needed = round(price - current_saved, 2) print(f'''You need {needed} more dollars''') if current_saved >= price: print(f'''you have {current_saved} dollars which is enough to purchase {product} for {price}$''') # 询问是否重启程序 restart = input("Do you want to start over? Yes or No: ").lower() if restart == "yes": continue else: break # 终止循环,退出程序 if add_a_second_product == "yes": product2 = input("Enter second product name: ") price2 = float(input("What is the price of the second product: ")) total_price = round(price + price2, 2) print(f'''You want to save towards purchasing {product.title()} and {product2.title()} which costs {total_price} dollars(Can)''') correct2 = input("is this correct, Yes or No: ").lower() if correct2 == "no": print("Re-enter correct data") continue # 回到循环开头,重新输入 if correct2 == "yes": current_saved2 = float(input("How much do you currently have saved: ")) needed_total = round(total_price - current_saved2, 2) print(f'''You need {needed_total} more dollars''') if current_saved2 >= price: print(f'''you have {current_saved2} dollars which is enough to purchase {product} for {price}$''') if current_saved2 >= total_price: print(f'''you have {current_saved2} dollars which is enough to purchase both {product} and {product2}''') # 询问是否重启程序 restart = input("Do you want to start over? Yes or No: ").lower() if restart == "yes": continue else: break
额外说明
.lower()处理用户输入,不管输入"No"、"NO"还是"no"都能正确识别continue会跳过当前循环的剩余代码,直接回到while True的开头,实现程序重启效果- 流程结束后增加了重启询问,不想继续时用
break终止循环退出程序
内容的提问来源于stack exchange,提问作者Carter Luscombe
相关产品推荐
相关产品推荐

