unexpected execution of Exceptions in python

不问归期 提交于 2019-12-20 05:52:13

问题


I am novice to python and i came up with this problem. i have made a simple program for calculator. In add function, i have used try- except. when this line is encountered (if decide== 'no' or decide== 'n':), it displays the print line "return(" You have exited ")" but it also throws the exception. I cant understand why.

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:


This works for me ....I suppose return(" You have exited ") is problem here and istead of sys.exit(0) try return 0 I dont know why its a problem but it works. I tried it for both yes and no conditions.

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)

output: Do you want to continue:

yes or no: re

wrong choice!!!

Error: <type 'exceptions.NameError'>


Do you want to continue:

yes or no: y

yes selected

calculator using functions

Choose your option:

1) Addition 2) Subtraction 3) Multiplication 4) Division 5) Quit calculator.py

Choose your option:


Do you want to continue:

yes or no: n

no selected

root@yogesh-System-model:~#



来源:https://stackoverflow.com/questions/22031848/unexpected-execution-of-exceptions-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!