Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在一段时间内中断程序-尝试并排除_Python - Fatal编程技术网

Python 在一段时间内中断程序-尝试并排除

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 我希望程序会中断,但它只会问“

如果用户输入“否”,我需要我的程序中断。此时,程序不会中断,当输入“否”时,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

我希望程序会中断,但它只会问“您想要答案的副本吗?”再次

继续评论,这应该可以:

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部分,以便将其放入问题面板中。感谢您的帮助您应该始终发布一段代码片段,以重现您面临的问题,看看我发布的答案是否有帮助?