Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print N to 1 Recursively

Print n down to one with recursive Python calls. Students compare work before a recursive call with work after it and identify the zero stopping condition.

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

In this one

  • Print before recursion
  • Shrink an argument
  • Stop at zero

How it works

  1. 1

    Return without printing at zero.

  2. 2

    Print the current n.

  3. 3

    Request the same function for n - 1.

Edge cases

Is zero printed?

Is zero printed?

No. The base case returns before print.

What if n is negative?

What if n is negative?

The decreasing calls do not reach zero and exhaust the recursion limit.

What's going on

This function prints n before making the smaller call. The visible output therefore follows the downward journey, not the later return journey.

For three, the calls print three, two, then one before reaching zero. The call stack still stores pending returns even though no printing remains afterward. A negative input never reaches zero with this decrement and eventually raises RecursionError.

Is zero printed? No. The base case returns before print.

What if n is negative? The decreasing calls do not reach zero and exhaust the recursion limit.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Where is print placed?

Pick an answer to check it.

Question 2

Is zero printed?

Pick an answer to check it.

Questions people ask

Is zero printed?

No. The base case returns before print.

What if n is negative?

The decreasing calls do not reach zero and exhaust the recursion limit.

Where is print placed?

Before the recursive call.