2017-11-03 123 views
-1

我试过异常处理和陷在了我的第一个程序,在这个程序我第一次继续在同时工作,但第二个一个不连续的环用Python 2继续在一段时间

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)? = ") 

第二个不同之处工作正常,但打印后的消息,它跳转到最后声明

请帮忙?

+0

我试图格式化你的代码,但你应该确保它准确地反映了你确实有。 –

+0

你为什么继续使用? – scharette

+1

是的,因为'finally'总是被执行。这就是整个问题。 –

回答

1

docs

一个最后条款离开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)? = ")