Home > Blockchain >  Evaluating a math function with two arguments in Python
Evaluating a math function with two arguments in Python

Time:11-23

Can someone explain how the correct answer here is 4? The var a here should be "2" according to the logic of the function I see as "a=inc(a,a)" should evaluate to undefined as you have replaced the value of a in this statement? What am I missing?

def inc(a,b=1):
    return(a b)
a=inc(1)
a=inc(a,a)
print(a)

CodePudding user response:

In Python, the interpreter first evaluates the left hand side of the code:

a = inc(a, a)

This means that it will first calculate "inc(a, a)", which will evaluate to "4", and then, it will replace the value of "a" with the value, "4", to get:

a = 4

CodePudding user response:

you are adding 1 1 first, then you are taking that sum or 2, and then adding it by its self again so a 4

def inc(a,b=1):
  return(a b) # adds 1 to a

a=inc(1) # a is 1   1 or 2
a=inc(a,a)# here you are adding 2   2
print(a) # results to a 4
  • Related