-1

In the following piece of code,

def makes_twenty(a,b):
     return a+b==20 or a==20 and b==20

Why does this input return False[makes_twenty(20,2)] while the following input returns True[makes_twenty(20,0)]?

Shouldn't the second input return False as b==20 is not being satisfied? What logic/concept am I missing here?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45

2 Answers2

2

You can always ask Python to print out how it parses your code using the ast (abstract syntax tree) module:

$ echo 'a+b==20 or a==20 and b==20' | python3 -m ast
Module(
   body=[
      Expr(
         value=BoolOp(
            op=Or(),
            values=[
               Compare(
                  left=BinOp(
                     left=Name(id='a', ctx=Load()),
                     op=Add(),
                     right=Name(id='b', ctx=Load())),
                  ops=[
                     Eq()],
                  comparators=[
                     Constant(value=20)]),
               BoolOp(
                  op=And(),
                  values=[
                     Compare(
                        left=Name(id='a', ctx=Load()),
                        ops=[
                           Eq()],
                        comparators=[
                           Constant(value=20)]),
                     Compare(
                        left=Name(id='b', ctx=Load()),
                        ops=[
                           Eq()],
                        comparators=[
                           Constant(value=20)])])]))],
   type_ignores=[])

The tree is a bit verbose, but you can see the topmost operation is OR, followed by a nested AND, i.e. Python parses your expression as

(a+b==20) or (a==20 and b==20)

(And, of course, the precedence order is well documented).

AKX
  • 152,115
  • 15
  • 115
  • 172
0

makes_twenty(20,0) returns true because the first condition is true; This is the execution order: a+b==20 or (a==20 and b==20)