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
相关产品推荐
相关产品推荐

