unexpected execution of Exceptions in python

后端 未结 1 883
我在风中等你
我在风中等你 2021-01-26 08:53

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 d

相关标签:
1条回答
  • 2021-01-26 09:31

    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:~#

    0 讨论(0)
提交回复
热议问题