为什么“a == x or y or z"?总是评估为真?

2022-01-19 00:00:00 python boolean boolean-expression

问题描述

我正在编写一个拒绝未经授权的用户访问的安全系统.

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

name = input("Hello. Please enter your name: ")
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.

为什么会发生这种情况?我已经明确声明,仅当 name 等于 Kevin、Jon 或 Inbar 时才授予访问权限.我也尝试了相反的逻辑,if Kevin";或乔恩"或Inbar"== name,但结果是一样的.

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 新手遇到的,他们可能难以将反向问题的知识应用到他们的问题中.

Note: this question is intended as the canonical duplicate target of this very common problem. There is another popular question How to test multiple variables against a single value? that has the same fundamental problem, but the comparison targets are reversed. This question should not be closed as a duplicate of that one as this problem is encountered by newcomers to Python who might have difficulties applying the knowledge from the reversed question to their problem.


解决方案

在许多情况下,Python 看起来和行为都像自然英语,但这是抽象失败的一种情况.人们可以使用上下文线索来确定Jon"和Inbar"是连接到动词equals"的宾语,但 Python 解释器更注重字面意思.

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":

逻辑上等价于:

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

对于用户 Bob,相当于:

Which, for user Bob, is equivalent to:

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

or 运算符选择第一个具有正 真值:

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

if "Jon":

自从乔恩"有一个正的真值,if 块执行.这就是导致访问被授予"的原因.无论给出的名称如何,都会被打印出来.

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.

所有这些推理也适用于表达式 if Kevin";或乔恩"或Inbar"== 名称.第一个值 Kevin" 为真,因此执行 if 块.

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. 使用多个 == 运算符显式检查每个值:

  1. Use multiple == operators to explicitly check against each value:

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

  • 组成一个有效值的集合(例如一个集合、一个列表或一个元组),并使用 in 运算符来测试成员资格:

  • Compose a collection of valid values (a set, a list or a tuple for example), and use the in operator to test for membership:

    if name in {"Kevin", "Jon", "Inbar"}:
    

  • 一般来说,第二个应该是首选,因为它更容易阅读,也更快:

    In general of the two the second should be preferred as it's easier to read and also faster:

    >>> import timeit
    >>> timeit.timeit('name == "Kevin" or name == "Jon" or name == "Inbar"',
        setup="name='Inbar'")
    0.4247764749999945
    >>> timeit.timeit('name in {"Kevin", "Jon", "Inbar"}', setup="name='Inbar'")
    0.18493307199999265
    


    对于那些可能想要证明 if a == b or c or d or e: ... 确实是这样解析的人.内置的 ast 模块提供了答案:


    For those who may want proof that if a == b or c or d or e: ... is indeed parsed like this. The built-in ast module provides an answer:

    >>> import ast
    >>> ast.parse("a == b or c or d or e", "<string>", "eval")
    <ast.Expression object at 0x7f929c898220>
    >>> print(ast.dump(_, indent=4))
    Expression(
        body=BoolOp(
            op=Or(),
            values=[
                Compare(
                    left=Name(id='a', ctx=Load()),
                    ops=[
                        Eq()],
                    comparators=[
                        Name(id='b', ctx=Load())]),
                Name(id='c', ctx=Load()),
                Name(id='d', ctx=Load()),
                Name(id='e', ctx=Load())]))
    

    可以看出,它是布尔运算符 or 应用于四个子表达式:比较 a == b;和简单的表达式 cde.

    As one can see, it's the boolean operator or applied to four sub-expressions: comparison a == b; and simple expressions c, d, and e.

    相关文章