Python- if和elif语句不能正常工作

时间:2015-11-07 20:07:59

标签: python

User_Input = str(input())
if "1" or "2" in User_Input:
    print("didn't work [1]")
    if "3" in User_Input:
        print("didn't work [2]")
    elif '4' not in User_Input:
        print('didnt work [3]')
elif '5' in User_Input:
    print('it worked')

当我使User_Input等于'5'时,它并没有说“它有效”,而是说 '没有工作[1]'和'没有工作[3]'这是不可能的,因为5不等于1或2所以它甚至不应该得到太多的线,打印('没有工作[3]')但不知何故它确实。请帮忙解释一下!

1 个答案:

答案 0 :(得分:5)

您正在混淆评估报表的方式,特别是您的or

以下是解释器如何评估它:

# Note: This is evaluated as two separate boolean checks
# as denoted by the parens, rather than one as you are
# intending.
if ("1") or ("2" in User_Input):  # "1" is a "truthy" value, e.g. not an empty string, so this is True, and ("2" in User_Input) is not evaluated due to "short circuiting".  Meaning no matter what input you get, this if is always True.

相反,您要查看的是User_Input字符串是否包含在您的任何值中:

if User_Input in ["1", "2"]:
    # Only happens when 1 or 2 is the user input

正在发生的事情被称为short circuiting。基本上这意味着如果第一次评估可以满足布尔运算的结果,则可以跳过其余的结果。

if True or False:  #  Since the first is True, the False is never evaluated

if False and True:  # Since this is an "and", and the first condition already failed, the True is never evaluated

现在将其推断为昂贵的函数调用(不仅仅是内置函数)。它可能会在更大的功能中节省大量时间。为了证明:

import time

def my_long_func():
    """Waits 5 seconds and returns False"""
    time.sleep(5)
    return False

def my_true_func():
    """Immediately returns True"""
    return True

if my_true_func() or my_long_func():
    print("This happens immediately, because of short circuiting.")

如果在解释器中运行^,您将看到打印立即发生,并且您的程序永远不会等待5s睡眠,因为它是不必要的(该函数永远不会被调用)。从本质上讲,这是一个简单的编程优化,我能想到的每种语言都会自动为您完成:)