Python-if和elif语句工作不正常
当我让用户输入等于“5”时,它并没有说“它工作了”,而是说Python-if和elif语句工作不正常,python,Python,当我让用户输入等于“5”时,它并没有说“它工作了”,而是说 “didnt work[1]”和“didnt work[3]”这是不可能的,因为5不等于1或2,所以它甚至不应该太长,可以打印(“didnt work[3]”),但不知怎的,它确实如此。请帮我解释一下 您混淆了语句的计算方式,特别是您的或 以下是口译员对其进行评估的方式: User_Input = str(input()) if "1" or "2" in User_Input: print("didn't work [1]")
“didnt work[1]”和“didnt work[3]”这是不可能的,因为5不等于1或2,所以它甚至不应该太长,可以打印(“didnt work[3]”),但不知怎的,它确实如此。请帮我解释一下 您混淆了语句的计算方式,特别是您的
或
以下是口译员对其进行评估的方式:
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')
相反,您试图查看的是用户\u输入
字符串是否在您的任何值中:
# 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.
正在发生的事情被称为。从本质上讲,这意味着如果布尔运算的结果可以通过第一次求值得到满足,则可以跳过其余的求值
if User_Input in ["1", "2"]:
# Only happens when 1 or 2 is the user input
现在将其外推到一个昂贵的函数调用(不仅仅是内置的)。在一个更大的函数中,它可能会节省很多时间。证明:
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
如果在解释器中运行^,您将看到打印立即发生,并且您的程序从不等待5s睡眠,因为这是不必要的(该函数从未调用)。本质上,这是一个简单的编程优化,我能想到的每种语言都会自动为您进行:)您混淆了语句的计算方式,特别是您的或
以下是口译员对其进行评估的方式:
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')
相反,您试图查看的是用户\u输入
字符串是否在您的任何值中:
# 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.
正在发生的事情被称为。从本质上讲,这意味着如果布尔运算的结果可以通过第一次求值得到满足,则可以跳过其余的求值
if User_Input in ["1", "2"]:
# Only happens when 1 or 2 is the user input
现在将其外推到一个昂贵的函数调用(不仅仅是内置的)。在一个更大的函数中,它可能会节省很多时间。证明:
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
如果在解释器中运行^,您将看到打印立即发生,并且您的程序从不等待5s睡眠,因为这是不必要的(该函数从未调用)。本质上,这是一个简单的编程优化,我能想到的每种语言都会自动为你做:)你只能在
中的每个中使用一个值,所以在用户输入中使用“1”或在用户输入中使用“2”。谢谢你,我现在就试用它。你只能在
中的每个中使用一个值,所以在用户输入中使用“1”或“2”在用户输入中
。谢谢你,我现在就试用。谢谢,它帮助很大:)我一定会把我遇到的问题发出去have@MattR没问题,祝你好运!如果在你有能力的时候它解决了你的问题,请接受答案!谢谢,帮了大忙:)我一定会把我遇到的问题发出去have@MattR没问题,祝你好运!如果在你有能力的时候它解决了你的问题,请接受答案!