【问题标题】:Python with 2 continue in a whilePython with 2 一会儿继续
【发布时间】:2026-01-10 21:15:02
【问题描述】:

我尝试了异常处理并卡在了我的第一个程序中,在这个程序中,我的第一个 continue in while 正在工作,但第二个没有继续循环

print("hello to divide")
o = "y"
while o == "y":
    try:
        x = int(input("enter first no. = "))
        y = int(input("enter second no. = "))
    except:
        print("please enter numeric value")
        continue
    try:
        z = x/y
        print(str(x) +"/"+str(y)+"="+str(z))
    except:
        print("please do not divide with 0(zero)")
        continue

    finally:
        o = input("do you want to do it again (y/n)? = ")

第二个 except 工作正常,但在打印消息后跳转到 finally 语句

请帮忙???

【问题讨论】:

  • 我尝试格式化您的代码,但您应该确保它准确地反映了您实际拥有的内容。
  • 你为什么使用 continue ?
  • 是的,因为finally总是被执行。这就是重点。
  • 非常感谢,我会确保它不会再次发生@juanpa.arrivillaga
  • 我使用 continue 所以 while 循环会再次执行,而在 finally 之前会执行

标签: python exception while-loop exception-handling continue


【解决方案1】:

来自docs

finally 子句总是在离开 try 之前执行 语句,是否发生异常。当异常 发生在try 子句中并且尚未由 except 子句(或者它发生在 exceptelse 子句中), 它在finally 子句执行后重新引发。这 finally 子句也会在“退出”时执行 try 语句的子句通过 breakcontinuereturn 声明。一个更复杂的例子:

我很确定你只是想要:

print("hello to divide")
o = "y"
while o == "y":
    try:
        x = int(input("enter first no. = "))
        y = int(input("enter second no. = "))
    except:
        print("please enter numeric value")
        continue
    try:
        z = x/y
        print(str(x) +"/"+str(y)+"="+str(z))
    except:
        print("please do not divide with 0(zero)")
        continue

    o = input("do you want to do it again (y/n)? = ")

【讨论】: