为什么`A == B或C或D`总是为真? [英] Why does `a == b or c or d` always evaluate to True?

查看:170
本文介绍了为什么`A == B或C或D`总是为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写拒绝访问未经授权的用户的安全系统。

I am writing a security system that denies access to unauthorized users.

import sys

print("Hello. Please enter your name:")
name = sys.stdin.readline().strip()
if name == "Kevin" or "Jon" or "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

它授予访问授权用户如预期,但它也让在未经授权的用户!

It grants access to authorized users as expected, but it also lets in unauthorized users!

Hello. Please enter your name:
Bob
Access granted.

为什么会发生这种情况?我已经清楚地说明,只授予访问时,名称等于凯文,乔恩,或跋。我也尝试了相反的逻辑,如果凯文或乔恩或跋==名称,但结果是一样的。

Why does this occur? I've plainly stated to only grant access when name equals Kevin, Jon, or Inbar. I have also tried the opposite logic, if "Kevin" or "Jon" or "Inbar" == name, but the result is the same.

推荐答案

在许多情况下,Python的外观和行为就像天然的英语,但是这就是那个抽象失败一例。人们可以利用上下文的线索,以确定乔恩和跋是对象加入动词等于,但Python的跨preTER更字面态度。

In many cases, Python looks and behaves like natural English, but this is one case where that abstraction fails. People can use context clues to determine that "Jon" and "Inbar" are objects joined to the verb "equals", but the Python interpreter is more literal minded.

if name == "Kevin" or "Jon" or "Inbar":

在逻辑上等同于:

is logically equivalent to:

if (name == "Kevin") or ("Jon") or ("Inbar"):

其中,为用户Bob,相当于:

Which, for user Bob, is equivalent to:

if (False) or ("Jon") or ("Inbar"):

操作员选择的第一个参数以积极的真值

The or operator chooses the first argument with a positive truth value:

if ("Jon"):

此外,由于乔恩有积极的真值,在如果块执行。这是什么原因,无论给出的名字被印有授予访问。

And since "Jon" has a positive truth value, the if block executes. That is what causes "Access granted" to be printed regardless of the name given.

这一切的推理也适用于前pression 如果凯文或乔恩或跋==名称。第一个值,凯文,是真实的,所以如果块执行。

All of this reasoning also applies to the expression if "Kevin" or "Jon" or "Inbar" == name. the first value, "Kevin", is true, so the if block executes.

有两种常用的方法正确地构建该条件。

There are two common ways to properly construct this conditional.


  1. 使用多个 == 运营商明确对证每个值:结果
    如果name ==凯文或名称==乔恩或名称==跋:

  1. Use multiple == operators to explicitly check against each value:
    if name == "Kevin" or name == "Jon" or name == "Inbar":

撰写有效值的序列,并在使用运算符来测试成员:结果
如果名字(凯文,乔恩,跋):

Compose a sequence of valid values, and use the in operator to test for membership:
if name in ("Kevin", "Jon", "Inbar"):

这篇关于为什么`A == B或C或D`总是为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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