Python 3.x 在函数定义中使用elif而不是else时显示异常的返回语句
我在函数定义中使用了Python 3.x 在函数定义中使用elif而不是else时显示异常的返回语句,python-3.x,Python 3.x,我在函数定义中使用了elif而不是else(每月的第天),执行函数时显示错误: 取消绑定LocalError:分配前引用的局部变量“月\日” 但是在使用else而不是elif之后,它没有显示任何错误 代码给出错误如下 def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True
elif
而不是else
(每月的第天),执行函数时显示错误:
取消绑定LocalError:分配前引用的局部变量“月\日”
但是在使用else
而不是elif
之后,它没有显示任何错误
代码给出错误如下
def is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year,month):
if is_leap == True:
month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
elif is_leap == False:
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return month_days[month-1]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
现在我已经修复了我的代码,但是这种异常现象背后的原因是什么呢???这是因为您没有正确调用函数
is\u leap
if is_leap == True:
函数是_leap
是参数化的,它需要一个参数year
,但调用时没有传递它
在if
和elif
两个位置,它必须是这样的
if is_leap(year) == True:
发生此错误是因为未执行任何块,无论是if
还是elif
,
所以你的月日
列表不会被创建
为了避免这样的错误,我编写了如下代码
def is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year,month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(year) == True:
month_days[1] = 29
return month_days[month-1]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
def foo1(年份:int)->bool:
“查找年份是否为闰年”
如果年份%4==0,年份%100!=0:
返回真值
返回年份%4==0,年份%100==0,年份%400==0
def foo2(年份:整数,月份:整数):
“查找一个月内的最大天数”
如果foo1(年)和月==2:
返回29
报税表[31,28,31,30,31,31,30,31,31,30,31][month-1]
感谢您解决问题,谢谢您的回答