中断程序,而一段时间是真的 - 尝试和例外



如果用户输入"no",我需要我的程序中断。目前,程序不会中断,当输入"否"时,尝试和除了重新启动

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

编辑

然而,更好的方法是使用带有break的无限循环:

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_answer_check并将值设置为 True 。如果你在 try...except 块中构建代码,你需要让它完整,而不仅仅是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")

相关内容

最新更新