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

Python条件判断逻辑错误:无论星期几均输出‘change day’求助

日期判断周末的代码逻辑错误排查

我写了一段判断任务日期是否为周末的代码,但不管当天是周几,都会输出“change day”提示,代码和运行结果如下:

原代码:

if week_Days[movePlates.weekday()] == "Saturday" or "Sunday":
    print("change day " + str(week_Days[movePlates.weekday()]))
else: 
     print("move plates on: " + str(movePlates))


if week_Days[readPlates.weekday()] == "Saturday" or "Sunday":
    print("change day " + str(week_Days[readPlates.weekday()]))
else: 
    print("read plates on: " + str(readPlates))

运行结果:

Change day Sunday
Change day Thursday


错误原因

问题出在or运算符的逻辑写法上。你写的A == "Saturday" or "Sunday"等价于(A == "Saturday") or "Sunday",而Python中非空字符串会被视为True,所以不管A对应的是星期几,这个条件永远成立,自然每次都执行print("change day...")。

修正方案

有两种正确的写法,推荐用更简洁的第二种:

  • 方式一:分别判断两次相等,用or连接
  • 方式二:用in运算符,判断日期是否在周末列表中

修正后的代码示例:

# 方式一:分别判断相等
current_day_move = week_Days[movePlates.weekday()]
if current_day_move == "Saturday" or current_day_move == "Sunday":
    print("change day " + current_day_move)
else: 
     print("move plates on: " + str(movePlates))

current_day_read = week_Days[readPlates.weekday()]
if current_day_read == "Saturday" or current_day_read == "Sunday":
    print("change day " + current_day_read)
else: 
    print("read plates on: " + str(readPlates))

# 方式二:用in运算符更简洁(推荐)
current_day_move = week_Days[movePlates.weekday()]
if current_day_move in ["Saturday", "Sunday"]:
    print("change day " + current_day_move)
else: 
     print("move plates on: " + str(movePlates))

current_day_read = week_Days[readPlates.weekday()]
if current_day_read in ["Saturday", "Sunday"]:
    print("change day " + current_day_read)
else: 
    print("read plates on: " + str(readPlates))

修改后,只有当日期是周六或周日时才会输出“change day”,其他日期会正常显示任务执行日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:25:07