访问函数返回变量时触发NameError(是否为执行顺序问题?)
问题解决:NameError: name 'leap_status' is not defined
错误原因
leap_status是is_leap函数内部的局部变量,函数外部以及其他函数(比如days_in_month)无法直接访问它。- 你调用
is_leap(year)时,没有把函数返回的闰年状态保存到变量中,导致days_in_month找不到需要的判断依据。
两种修复方案
方案一:保存is_leap的返回值,传给days_in_month
修改代码如下:
def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap_status = True else: leap_status = False else: leap_status = True else: leap_status = False return leap_status def days_in_month(month, leap_status): # 修改参数,接收leap_status if leap_status: month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] else: month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return month_days[month - 1] # 用户输入年份 year = int(input()) # 保存闰年判断结果 leap_status = is_leap(year) # 用户输入月份 month = int(input()) # 传入闰年状态计算天数 days = days_in_month(month, leap_status) print(days) # 可添加打印查看结果
方案二:在days_in_month内部直接调用is_leap
这种方式无需额外传递变量,函数内部自行获取闰年状态:
def is_leap(year): if year % 4 == 0: if year % 100 == 0: return year % 400 == 0 else: return True else: return False def days_in_month(year, month): # 直接在函数内调用is_leap获取闰年状态 if is_leap(year): month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] else: month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return month_days[month - 1] # 用户输入年份 year = int(input()) # 用户输入月份 month = int(input()) # 直接调用函数计算天数 days = days_in_month(year, month) print(days)
额外优化建议
is_leap函数可以简化为一行代码,逻辑更清晰且与原逻辑完全一致:
def is_leap(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
内容的提问来源于stack exchange,提问作者J W
相关产品推荐
相关产品推荐

