Python “and” operator with ints

前端 未结 3 1047
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 18:00

What is the explanation for this behavior in Python?

a = 10
b = 20
a and b # 20
b and a # 10

a and b evaluates to 20, while

3条回答
  •  难免孤独
    2021-01-11 18:25

    The documentation explains this quite well:

    The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    And similarly for or which will probably be the next question on your lips.

    The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

提交回复
热议问题