在python中意外执行异常

时间:2014-02-26 04:36:38

标签: python-2.7 exception-handling

我是python的新手,我想出了这个问题。我已经为计算器做了一个简单的程序。在添加功能中,我使用了try- except。当遇到这一行时(如果决定=='不'或决定=='n':),它会显示打印行“return(”你已退出“)”但它也会抛出异常。我不明白为什么。

import sys

def menu():

    print "calculator using functions"
    print "Choose your option:"
    print " "
    print "1) Addition"
    print "2) Subtraction"
    print "3) Multiplication"
    print "4) Division"
    print "5) Quit calculator.py"
    print " "
    return input ("Choose your option: ")


def add(a,b):
    try:
        print a, "+", b, "=", a + b
        print " Do you want to continue: "
        decide=raw_input("yes or no: ")
        if decide== 'no' or decide== 'n':
            return(" You have exited ")
            sys.exit(0)
        elif decide=='yes' or decide== 'y':
            menu()
        untrusted.execute()

    except:
        print "wrong choice!!!"
        e = sys.exc_info()[0]
        print "Error: %s" % e
        sys.exit(0) 

1 个答案:

答案 0 :(得分:0)

这对我有用....我认为return(" You have exited ")在这里是问题,而不是sys.exit(0)尝试return 0我不知道它为什么会出现问题但它有效。我尝试了既可以也可以没有条件。

import sys



def menu():

print "calculator using functions"
print "Choose your option:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
return input ("Choose your option: ")


def add(a,b):
try:
    print a, "+", b, "=", a + b
    print " Do you want to continue: "
    decide=raw_input("yes or no: ")
    if decide== 'no' or decide== 'n':
        return "n"
        #sys.exit(0)
    elif decide=='yes' or decide== 'y':
        return "y"
    untrusted.execute()

except:
    print "wrong choice!!!"
    e = sys.exc_info()[0]
    print "Error: %s" % e
    sys.exit(0)

while(True):
selected_option=menu()
if(selected_option == 1):
    print "Enter first number:"
    no1 = raw_input()
    print "Enter second number:"
    no2 = raw_input()
    option=add(no1,no2)
    if(option == 'y'):
        print "yes selected"
        continue
    if(option=='n'):
        print "no selected"
        sys.exit(0)

输出: 你想继续吗?

是或否:重新

错误的选择!!!

错误:<type 'exceptions.NameError'>


你想继续吗?

是或否:y

是选择

使用函数的计算器

选择您的选项:

1)增加 2)减法 3)乘法 4)分部 5)退出calculator.py

选择您的选项:


你想继续吗?

是或否:n

没有选择

root @ yogesh-System-model:〜#