0

f(n-1)+100

Could plase help me understand why this code returns 300? I think it shoud return 102. What am I missing? def f(n): if n==0: return 0 else: return f(n-1)+100 print(f(3))

2nd May 2019, 10:20 AM
Peter Pjecha
Peter Pjecha - avatar
5 Réponses
+ 5
Put the code on pythontutor and visualize it there. Then things should become clear.
2nd May 2019, 12:10 PM
Thoq!
Thoq! - avatar
+ 4
This is recusion f(3) = f(2) + 100 = ( f(1) + 100 ) + 100 = ( ( f(0) + 100 ) + 100 ) +100 = ( ( 0 + 100 ) + 100 ) + 100 If you understand this, try coding a power function, a factorial function and a Fibonnaci, for practice.
2nd May 2019, 1:07 PM
Gordon
Gordon - avatar
+ 2
It will make 100+100+100 this is why you see 300 and not 102...
2nd May 2019, 10:22 AM
Werg Serium
Werg Serium - avatar
+ 2
pythontutor.com It is a website where you can visualize your code (limited to python and about 6 other languages). It is great for understanding and/or debugging short parts of code. You can't really use it for bigger stuff because it is limited to 1000 steps and about 100 lines of code. You can also get live-help there. It is not a competitor of sololearn. So I don't feel bad telling people about it here.
2nd May 2019, 1:24 PM
Thoq!
Thoq! - avatar
0
Thoq what is pythontutor?
2nd May 2019, 1:00 PM
Werg Serium
Werg Serium - avatar