Print N to 1 Recursively

Print numbers from n to 1 using recursion.

IntermediatePhase 3 - Level 1: Basic RecursionExample 3 of 10
print-n-to-1-recursively.py
1def print_n_to_1(n):
2 # Base case
3 if n == 0:
4 return
5
6 # Recursive case: print current, then smaller
7 print(n)
8 print_n_to_1(n - 1)
9
10# Test
11n = int(input("Enter n: "))
12print_n_to_1(n)

Output

Enter n: 5
5
4
3
2
1

What's going on

Print current number, then recurse with n-1.

Key Concepts:

Base case: n == 0, return
Print n first, then recurse
Decreases from n to 1