我是 python 新手,我想出了这个问题。我为计算器编写了一个简单的程序。在add函数中,我使用了try- except。当遇到这一行时(如果decide=='no'或decide=='n':),它会显示打印行“return(”You has exited“)”,但它也会抛出异常。我不明白为什么。
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)
这对我有用......我想return(" You have exited ")
这里有问题而不是sys.exit(0)
try 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)
输出:
你想继续吗:
是或否:重新
错误的选择!!!
Error: <type 'exceptions.NameError'>
你想继续吗:
是或否: y
是,已选择
使用函数的计算器
选择您的选项:
1)加法
2)减法
3)乘法
4)分部
5)退出calculator.py
选择您的选项:
你想继续吗:
是或否:n
没有选择
root@yogesh-系统模型:~#
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)