Print 1 to N Recursively

Print numbers from 1 to n using recursion.

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

Output

Enter n: 5
1
2
3
4
5

What's going on

Recursively solve smaller problem, then print current number.

Key Concepts:

Base case: n == 0, return
Recursive case: print 1 to n-1, then print n
Function calls itself with smaller value