How do boolean operators work in 'if' conditions?

后端 未结 3 656
有刺的猬
有刺的猬 2021-01-23 06:50

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 expla

3条回答
  •  旧巷少年郎
    2021-01-23 07:51

    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.)

提交回复
热议问题