如果语句没有正确执行

时间:2014-02-26 05:06:23

标签: python-2.7

我是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) 

输出:

calculator using functions
Choose your option:

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

Choose your option: 1
Add first No: 343
Add second No: 5435
343 + 5435 = 5778
 Do you want to continue: 
yes or no: n
 You have exited 
wrong choice!!!
calculator using functions
Choose your option:

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

Choose your option: 

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)