You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python不导入datetime用for循环计算年剩余天数代码错误排查

代码错误分析
  • 核心计算逻辑错误:仅在循环前给month_day赋值为当前输入月份的天数,循环累加所有已过月份的天数时都复用了这个值,比如输入12月就会累加11次31天,完全没有考虑不同月份的天数差异,是结果出错的主要原因。
  • 有效性校验逻辑完全失效:月份校验的分支和年份校验的分支为同级elif关系,只要年份校验的任意分支命中,月份校验就不会执行;同时校验条件写为month < 1 and month > 12,逻辑矛盾永远不会触发,应改为month < 1 or month > 12。
  • 循环终止条件错误:平年计算的循环中设置了if month == 1: break,会导致少累加前面多个月份的天数。
  • 变量覆盖问题:直接把存储年份数值的year变量修改为闰年标识字符串,后续如果需要用到年份数值时无法获取,建议单独使用变量存储闰年判断结果。
修正后代码
day = int(input("输入日期:"))
month = int(input("输入月份:"))
year = int(input("输入年份:"))
days_passed = 0
is_leap = False

# 有效性校验
if year <= 0:
    print("请输入有效的年份")
    exit()
if month < 1 or month > 12:
    print("请输入有效的月份")
    exit()

# 闰年判断
if year % 4 == 0:
    if year % 100 == 0:
        is_leap = year % 400 == 0
    else:
        is_leap = True
else:
    is_leap = False

# 日期合法性校验
current_month_max_day = 29 if is_leap and month == 2 else \
    28 if month == 2 else \
    31 if month in [1,3,5,7,8,10,12] else 30
if day < 1 or day > current_month_max_day:
    print("请输入有效的日期")
    exit()

# for循环计算已过天数
for m in range(1, month):
    if m == 2:
        days_passed += 29 if is_leap else 28
    elif m in [1,3,5,7,8,10,12]:
        days_passed += 31
    else:
        days_passed += 30
days_passed += day

# 计算剩余天数
days_total = 366 if is_leap else 365
days_left = days_total - days_passed

print("已过天数:", days_passed)
print("剩余天数:", days_left)

内容的提问来源于stack exchange,提问作者mesut.a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:06:04