如何在“如果”条件布尔运算符的工作? [英] How do boolean operators work in 'if' conditions?
问题描述
我目前新的Python,我试图运行code的几行简单。我不明白的Python是如何评估的如果的语句之后此语法。任何解释将AP preciated。
I am currently new to Python and am trying to run a few simple lines of code. I cannot understand how Python is evaluating this syntax after the if statement. Any explanations will be appreciated.
number = int(raw_input("Enter number : "))
if number == (1 or 2 or 3):
print "Match"
else:
print "No match"
只有整数1屈服一个积极的结果和其他任何数字,包括2,3经过的其他的分支。条件可以表述为如下唯一:
Only the integer 1 yield a positive result and any other numbers including 2 and 3 go through the else branch. Can the conditions be stated as the following only?:
if number == 1 or number == 2 or number == 3:
感谢您。
推荐答案
Python有布尔值,如真
和假
并且它还具有的 falsy 值,如任何空列表,元组,或者字典,一个空字符串, 0
和无
。 Truthy值是是相反的,也就是被定义的东西。
Python has boolean values, such as True
and False
, and it also has falsy values, such as any empty list, tuple, or dictionary, an empty string, 0
, and None
. Truthy values are the opposite of that, namely anything that's defined.
Python中的或
的评估和短circuts在第一元素,它返回一个值truthy 的上
Python's or
evaluates and short-circuts on the first element that returns a truthy value.
所以,前pression (1或2或3)
是要返回 1
。
So, the expression (1 or 2 or 3)
is going to return 1
.
如果您想比较的所有的元素,那么你在关键字寻找:
If you want to compare against all elements, then you're looking for the in
keyword:
if number in (1, 2, 3):
# Do logic
这篇关于如何在“如果”条件布尔运算符的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!