Python Recursion
down(3) writes 3, then 2, then 1. The name down is used inside down, and each step hands over a number one smaller than the one it received.
The line if n == 0: return is the stop. When n is 0, that line runs and down is not used again. Leave that line out and the steps never end, so the program does not finish. That broken form is not shown below.
def down(n):
if n == 0:
return
print(n)
down(n - 1)
down(3)
The screen shows 3, then 2, then 1. print runs before the next down. down(1) writes 1 and then reaches down(0). down(0) hits the stop, writes nothing, and the program finishes.
Move print to the line after down(n - 1). The smaller numbers are written first, because each step waits until the inner one has finished.
def down(n):
if n == 0:
return
down(n - 1)
print(n)
down(3)
The screen shows 1, then 2, then 3. down(0) still writes nothing. The prints run on the way back, so 1 is written before 2, and 2 before 3.
down(0) on its own never reaches print. The stop runs at once.
def down(n):
if n == 0:
return
print(n)
down(n - 1)
down(0)
The screen stays empty, and the program finishes. n is already 0, so print and the next down are skipped.
Reading the screens wrong
The second program is not 3, then 2, then 1. That order belongs to the first program, where print comes first. Delete if n == 0: return from either program and the steps do not end. Do not run that version.
The next page is a list of values. This page only shows a function that uses its own name, and the line that stops it at 0.
Trace the numbers
- What does the first program write, first and then?
- What does the second program write, first and then?
- What does the third program write?
- You delete the stop at 0. Does the program finish?
What down does
The name down inside down, with n - 1, is what walks from 3 down to 1. Print before that step writes 3, then 2, then 1. Print after it writes 1, then 2, then 3. if n == 0: return is why the program finishes. down(0) writes nothing.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top