question archive Why does this equal 4 def inc(a,b=1): return(a+b) a=inc(1) a=inc(a,a) print(a)
Subject:Computer SciencePrice:2.86 Bought11
Why does this equal 4
def inc(a,b=1):
return(a+b)
a=inc(1)
a=inc(a,a)
print(a)
#inc function takes two parameter a and b, where parameter b default value is set to 1 #so if parameter b is not specified during function call it takes its value as 1 def inc(a,b=1): #returns sum of a and b return(a+b) #calling inc function with single parameter 1, so parameter a becomes 1 # and b is not specified so it becomes 1(its default value) a=inc(1) #result is, value of a is 2(1+1) now #calling inc function again with two parameters both same(a) whose values are 2 #since we are passing value 2 to parameter b this time, it takes value as 2 a=inc(a,a) #result is value of a is 4(2+2) this time #print value of a it is 4. print(a)
Step-by-step explanation
1) Above is your program with inc function, I have added comments to explain it better
2) basically it has inc function which takes two parameter a and b, where parameter b default value is set to 1, so if parameter b is not specified during function call it takes its value as 1
3) In first inc function call "a=inc(1) ", we have specified value for a and b value is not specified, so function takes value of a as 1 and value of b also as 1(its default value).
4) It adds up and return 2 which gets assigned to a again
5) in second function call "a=inc(a,a)", we have specified value for a and b as a which is 2, so this function adds up 2+2 and return 4
6) result 4 is again assign to a and printed.
7) so output is 4