+ 1

Can any one explain why the result is 15 and not 9 ?

def func(level): if level==1: return 1 else: return level + func(level-1) print(func(5))

31st Oct 2017, 8:28 PM
Ahmed Kamal
Ahmed Kamal - avatar
4 Answers
+ 4
When level reaches 1 the if statement is true: if level == 1 return 1 So, we are no longer calling the function over again when level equals to 1. This is what it would look like going through this step by step: First call the function: func(5) Now: is level == 1 true? No, level equals 5. return level + func(level-1) Is equivalent to: return 5 + func(4) What is func(4) equal to? is level == 1 true? No, level equals 4. return level + func(level-1) is equivalent to: return 4 + func(3) What is func(3) equal to? is level == 1 true? No level equals to 3. return level + func(level-1) Is equivalent to: return 3 + func(2) What is func(2) equal to? is level == 1 true? No level equals 2. return level + func(level-1) Is equivlent to: return 2 + func(1) What is func(1) equal to? is level == 1 true? Yes! return 1 Now, func(1) = 1. So, func(2) = 2 + func(1) = 2 + 1 = 3 So, func(3) = 3 + func(2) = 3 + 3 = 6 So, func(4) = 4 + func(3) = 4 + 6 = 10 So, func(5) = 5 + func(4) = 5 + 10 = 15 Final answer: 15
31st Oct 2017, 9:07 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
5 + 4 + 3 + 2 + 1 = 15
31st Oct 2017, 8:50 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
why did the program done a loop without any loop tools as while and for ??? why the answer is not only 5+4 = 9 can you please explain
31st Oct 2017, 9:00 PM
Ahmed Kamal
Ahmed Kamal - avatar
0
thanks alot
31st Oct 2017, 9:41 PM
Ahmed Kamal
Ahmed Kamal - avatar