How do boolean operators work in 'if' conditions?

心已入冬 提交于 2019-12-31 04:37:04

问题


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"

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:

Thank you.


回答1:


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's or evaluates and short-circuts on the first element that returns a truthy value.

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



回答2:


You probably want:

if number in (1, 2, 3):



回答3:


The or operator takes two arguments, on its left and right sides, and performs the following logic:

  1. Evaluate the stuff on the left-hand side.
  2. If it is a truthy value (e.g, bool(x) is True, so it's not zero, an empty string, or None), return it and stop.
  3. Otherwise, evaluate the stuff on the right-hand side and return that.

As such, 1 or 2 or 3 is simply 1, so your expression turns into:

if number == (1):

If you actually mean number == 1 or number == 2 or number == 3, or number in (1, 2, 3), you'll need to say that.

(Incidentally: The and operator works the same way, except step 2 returns if the left-hand-side is falsey.)



来源:https://stackoverflow.com/questions/18884818/how-do-boolean-operators-work-in-if-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!