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

Python闰年判断代码返回ValueError: substring not found错误的咨询

解决闰年判断程序的ValueError问题

你的问题出在使用str.index("0")和str.rindex("0")来检测年份末尾是否为两个零——当年份里没有"0"时,这两个方法会因为找不到子串直接抛出ValueError。其实完全没必要用字符串操作来判断整百年,用数学取模的方式更简单可靠,还不会触发错误。

先明确标准的闰年判断逻辑:

  • 能被4整除但不能被100整除 → 是闰年
  • 能被400整除 → 是闰年
  • 其他情况 → 不是闰年

下面是修改后的完整代码:

print("Did you know that the last leap year was in 2020?")
print("To find out if a year is a leap year, use this program")

valid = False

while not valid:
    year = input("Please enter a year\n")
    # 统一处理输入验证逻辑,避免重复input调用
    if not year or not year.isnumeric() or len(year) != 4:
        print("Error. Please enter a year - it should be 4 digits long.")
        continue
    # 输入验证通过,转换为整数
    year = int(year)
    valid = True
    
    # 标准闰年判断逻辑
    if year % 400 == 0:
        print(f"{year} is a leap year")
    elif year % 100 == 0:
        print(f"{year} is not a leap year")
    elif year % 4 == 0:
        print(f"{year} is a leap year")
    else:
        print(f"{year} is not a leap year")

关键改动说明:

  • 替换整百年判断方式:用year % 100 == 0判断是否为整百年,彻底避免字符串查找的报错问题;
  • 优化输入验证:把空输入、非数字、长度不符的情况合并判断,用continue回到循环开头,去掉重复的input调用,逻辑更简洁;
  • 简化分支逻辑:按照标准闰年规则排序判断条件,可读性更强,覆盖所有情况。

内容的提问来源于stack exchange,提问作者Azalea-Delphinium

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:17:27