简单的布尔不等式运算符错误 [英] Simple boolean inequality operators mistake

查看:117
本文介绍了简单的布尔不等式运算符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用不等号运算符,我必须定义一个过程weekend,该过程将字符串作为输入并返回布尔值True(如果它是'Saturday'或'Sunday',否则返回False).

Using inequality operators, I have to define a procedure weekend which takes a string as its input and returns the boolean True if it's 'Saturday' or 'Sunday' and False otherwise.

这是我的代码

def weekend(day):
    if day != 'Saturday' or day != 'Sunday':
        return False
    else:
        return True

这似乎每天都会返回False,我不知道为什么,从逻辑上讲,它可以正常工作……有人可以解释一下吗?

This seemingly returns False to every day, I don't know why, logically it would work... Can anyone please explain?

推荐答案

固定版本:

Fixed version:

if day != 'Saturday' and day != 'Sunday'

更好的版本:

Better version:

return day in ['Saturday', 'Sunday']

为什么or不起作用:

使用or时,您的状况将显示为如果今天不是星期六或今天不是星期日".现在,将今天"替换为星期六":

When you use or, your condition would read something like "if today is not Saturday or today is not Sunday". Now replace "today" by "Saturday":

如果星期六不是星期六或星期六不是星期日

If Saturday is not Saturday or Saturday is not Sunday

星期六不是星期六"的陈述显然是错误的,而星期六不是星期日"的陈述显然是正确的,因此整个陈述变成如果是false或true",这始终是正确的.

The statement "Saturday is not Saturday" is obviously false and "Saturday is not Sunday" is obviously true, so the entire statement becomes "if false or true", which is always true.

将"today"替换为"today",您会发现该句子的求值结果始终是以下其中一个句子:

Replace "today" by any other day and you will find that the sentence always evaluates to one of these sentences, which are always true:

if True or False  # day = Sunday
if False or True  # day = Saturday
if True or True   # any other day

这篇关于简单的布尔不等式运算符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆