Python 在一段时间内中断程序-尝试并排除
如果用户输入“否”,我需要我的程序中断。此时,程序不会中断,当输入“否”时,try和except将重新启动Python 在一段时间内中断程序-尝试并排除,python,Python,如果用户输入“否”,我需要我的程序中断。此时,程序不会中断,当输入“否”时,try和except将重新启动 while final_answer_check == True: try: final_answer = str(input("Do you want a copy of the answers?")) if final_answer.lower() == "no": final_answer_check = False 我希望程序会中断,但它只会问“
while final_answer_check == True:
try:
final_answer = str(input("Do you want a copy of the answers?"))
if final_answer.lower() == "no":
final_answer_check = False
我希望程序会中断,但它只会问“您想要答案的副本吗?”再次继续评论,这应该可以:
final_answer_check = True # a boolean flag
while final_answer_check: # while the flag is set to true
try:
final_answer = str(input("Do you want a copy of the answers?"))
if final_answer.lower() == "no":
final_answer_check = False
except:
pass
编辑:
Do you want a copy of the answers?no
Process finished with exit code 0
但是,更好的方法是使用带有中断的无限循环:
while True:
try:
final_answer = input("Do you want a copy of the answers?")
if final_answer.lower() == "no":
break
except:
pass
输出:
Do you want a copy of the answers?no
Process finished with exit code 0
首先,您需要定义变量final\u answer\u check
,并将值设置为True
。如果您在try…块中构建代码,除了
,您需要使其完整,而不仅仅是try
final_answer_check = True
while final_answer_check == True:
try:
final_answer = str(input("Do you want a copy of the answers?"))
if final_answer.lower() == "no":
final_answer_check = False
else:
final_answer_check = True
except:
print ("your another code should be here")
输入已经在strw中。你的except块在哪里?噢,循环在哪里?DirtyBit-我已经删除了except和loop部分,以便将其放入问题面板中。感谢您的帮助您应该始终发布一段代码片段,以重现您面临的问题,看看我发布的答案是否有帮助?