我是Python的新手,所以如果我的问题很愚蠢,请原谅我,但是,我不明白下面两个函数之间有什么区别,为什么第二个函数在使用异常时可以工作,而第一个函数却不行。我试着把'result'换成'return',但是没有用。我想我的缺失参数的条件是不正确的,但是即使我把它去掉,只留下了 "exception"。回 "缺月但还是没有打印出异常。
谢谢你的帮助。
def after_n_months(year, month):
try:
result year + (month // 12)
except TypeError:
return 'month missing' if month is None else 'year missing'
print(after_n_months( 2000, ))
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
return "division by zero!"
print(divide(2,0))
这是因为TypeError异常是在你输入函数之前就被捕获的。
试试这个吧
def after_n_months(year, month):
return year + (month // 12)
try :
print(after_n_months(2000))
except:
print("error")
EDIT : 为了测试你的功能,你也可以把None放入
def after_n_months(year, month):
try:
return year + (month // 12)
except TypeError:
return 'month missing' if month is None else 'year missing'
print(after_n_months( 2000 ))
print(after_n_months(2000, None))
print(after_n_months(None, 12))
EDIT2:你也可以把你的函数输入放在None里,像这样。
def after_n_months(year = None, month = None):
try:
return year + (month // 12)
except:
if year is None:
print("Year missing")
if month is None:
print("Month is missing")
after_n_months(5,12)
after_n_months(year=5)
after_n_months(month=12)