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))
5 Réponses
+ 5
Put the code on pythontutor and visualize it there. Then things should become clear.
+ 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.
+ 2
It will make 100+100+100 this is why you see 300 and not 102...
+ 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.
0
Thoq what is pythontutor?