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

Python字符串条件判断中if != 搭配or不生效问题求助

你遇到的是布尔逻辑判断的常见错误,当前代码的if条件永远为真,永远不会进入else分支。

错误原因

按照你写的if today != 'Sun' or today != 'Sat'逻辑:

  • 当输入为Sun时,today != 'Sat'成立,整个or判断结果为真
  • 当输入为Sat时,today != 'Sun'成立,整个or判断结果为真
  • 当输入为其他工作日时,两个判断都成立,结果仍为真

所有输入场景下or运算结果都为真,所以永远只会输出Go to work!。

修复方案

方案1:将or替换为and

符合德摩根逻辑定律,只有同时不等于周六和周日时,才判定为工作日:

today = input('Enter Day of the week (Sun, Mon, Tue and etc) ')
if today != 'Sun' and today != 'Sat':
     print ('Go to work!')
else:
   print('Weekend!!')

方案2:使用in判断简化逻辑(可读性更高)

直接判断输入值是否在周末集合内,更符合人类阅读习惯:

today = input('Enter Day of the week (Sun, Mon, Tue and etc) ')
if today not in {'Sat', 'Sun'}:
     print ('Go to work!')
else:
   print('Weekend!!')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:09:03