Print Numbers In A Range Without Loops In Python

In this tutorial, we will be looking at a Python program to print numbers in a range without loops. Yes, without any loops! We will be using the following Python concepts:

  • if…else statements
  • functions
  • recursion

Numbers in a Range without Loops

We will be making a recursive function call to print the numbers. We will be taking a lower and upper limit from the user and printing numbers including the limits, i.e. inclusive.

def print_num(lower, upper):
    if(upper + 1 > lower):
        print_num(lower, upper - 1)
        print(upper)

lower = int(input("Enter lower limit: "))
upper = int(input("Enter upper limit: "))

print_num(lower, upper)

First, we ask the user to input the lower and upper bound of the range using int(input(“Enter lower bound: “)) and int(input(“Enter upper bound: “)). Here, input() prints the message on the console and also reads the input given as a string. But we want the input to be an int so that we can perform mathematical operations on them and for that we use int().

print_num() is our recursive function. It takes two arguments – lower limit and upper limit. Inside the function we compare upper + 1 (this is so that upper is included in the range) with lower limit. If the condition is met, i.e. it is True then we make a recursive call to print_num() with parameters as upper – 1 and lower. This continues till upper becomes equal to lower. At this point all the print statements that were stored on the call stack are printed.

Lets take an example for better understanding. Let lower = 2 and upper = 5. Now the function calls made are:
print_num(2, 5) –> print_num(2, 4) –> print_num(2, 3 ) –> print_num(2, 2) –> print_num(2,1)
At print_num(2,1) the condition fails and the program prints all the upper values from the previous function calls.

Output

Enter lower limit: 2
Enter upper limit: 5
2
3
4
5

So here it is, a simple and fun program to print numbers in a range without using loops in Python.

Also read,

Leave a Reply

Your email address will not be published.