Python: Print Numbers 1 to N Recursively

1. Introduction

Often in programming, we come across situations where we want to perform a task without using the typical approach. One such task might be printing numbers from 1 to n without using loops. This can be achieved using recursion in Python.

2. Program Overview

1. Define a recursive function to print numbers.

2. Take user input for the value of n.

3. Call the recursive function with n as an argument.

3. Code Program

# Python program to print numbers from 1 to n without using loops

def print_numbers(n):
    """Recursive function to print numbers from 1 to n."""
    if n > 0:

# Taking user input
n = int(input("Enter the value of n: "))

# Calling the recursive function


(For an input of 5)
Enter the value of n: 5

4. Step By Step Explanation

1. We start by defining a recursive function print_numbers that takes a single argument n.

2. Inside this function, if n is greater than 0, we recursively call print_numbers with n-1 as the argument. This step ensures that the numbers are printed in ascending order.

3. After the recursive call, we print the current value of n.

4. Outside the function, we prompt the user to input a number (the value of n) and call our recursive function with this value.

5. As a result, numbers from 1 to n are printed in sequence. For instance, when the user enters 5, the numbers 1 through 5 are printed as showcased in the output.