In this post, we will learn how to print numbers from 1 to N using recursion in Python, along with a detailed explanation and example.

But before we jump into this topic, you must understand recursion and how it works. For a brief overview and better understanding of recursion, you can refer to this article.

Now, let’s come to the topic. To print numbers from 1 to N using recursion in Python, you need to identify the base case and understand how to call the function recursively.

For the base case, one approach is as follows: if we want to print numbers from 1 to n, let’s say n=10. In the first iteration, we print the current value, which is 1. To achieve this, we can declare a default starting value of 1. So, our base case should be: if the current value exceeds n, then return (or exit the recursion).

For the recursive step, first print the current value, and then call the function recursively with the next value (current + 1).

Let’s see how we can implement it programmatically.

Source Code

def print_1_to_n(n,current=1):
    if current > n:  # base case
        return
    print(current)    # print current value
    print_1_to_n(n,current+1) # call function recursively with current + 1 
    

# call the function with n = 10
print_1_to_n(10)

Output

1
2
3
4
5
6
7
8
9
10

Alternative method

There is another approach where you first call the recursive function and then print nnn. This works because recursion uses a stack to store function calls, and the last function call is resolved first (a Last-In-First-Out approach). As a result, the smallest value, 1, is printed first, followed by the rest in ascending order.

For this approach, the base case should be defined as follows: if n=1, return (or exit the recursion).

Let’s see how we can implement it programmatically.

Source Code

def print_1_to_n(n):
    if n==0:   #base case
        return
    print_1_to_n(n-1)   # recursive call (before printing the value)
    print(n)

# test the function
print_1_to_n(10)

Output

1
2
3
4
5
6
7
8
9
10
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment