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

Python代码出现SyntaxWarning: invalid decimal literal错误求助

日期验证Python代码错误排查

直接语法错误原因

看报错的第6行代码:

if month == 1 or not day < 31 or month == 2 or not day < 28 or month == 4 and not day < 30 or month == 5 and not day < 31 or month == 6 and not day < 30 or month == 7 and not day < 31 or month == 8 and not day < 31 or month == 9 and not day < 30 or month == 10 and not day < 31or month == 11 and not day < 30 or month == 12 and not day < 31:

其中month == 10 and not day < 31or month == 11这部分,31和or之间没有空格,Python会将31or识别为一个无效的十进制字面量,直接触发SyntaxWarning: invalid decimal literal警告。只要在31和or之间加个空格,这个语法问题就能解决,但你的代码逻辑还有更严重的问题。

逻辑错误分析

原代码的条件判断逻辑完全混乱:

  • 比如month == 1 or not day < 31,意思是只要月份是1月,不管天数是否合法都会报错,这和验证日期的目的完全相反。
  • and和or的优先级没做分组处理,导致整个条件的判断逻辑完全不符合预期,根本无法正确验证日期。

修正后的代码

按照正确的日期验证逻辑,先检查月份范围,再根据月份确定最大天数,最后验证天数是否合法:

day = int(input("Enter a day (1-31): "))
month = int(input("Enter a month (1-12): "))

# 验证月份范围
if month < 1 or month > 12:
    print("Error. Month must be between 1 and 12.")
else:
    # 根据月份确定当月最大天数
    max_day = 31
    # 4、6、9、11月只有30天
    if month in (4, 6, 9, 11):
        max_day = 30
    # 2月默认按平年28天处理,如需支持闰年可添加额外判断
    elif month == 2:
        max_day = 28
    
    # 验证天数范围
    if day < 1 or day > max_day:
        print(f"Error. Day must be between 1 and {max_day} for this month.")
    else:
        print("Date is valid.")

内容的提问来源于stack exchange,提问作者Zane Hedger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:31:09