Python Program to Print Numbers in a Range Without using Loops

This is a Python Program to print all numbers in a range without using loops.

Problem Description

The program takes in the upper limit and prints all numbers within the given range using recursive function.

Problem Solution

1. Define a recursive function.
2. Define a base case for that function that the number should be greater than zero.
3. If number is greater than 0, call the function again with the argument as the number minus 1.
4. Print the number.
5. Exit.

Program/Source Code

Here is source code of the Python Program to print all numbers in a range without using loops. The program output is also shown below.

def printno(upper):
    if(upper>0):
        printno(upper-1)
        print(upper)
upper=int(input("Enter upper limit: "))
printno(upper)
Program Explanation

1. User must enter the upper limit of the range.
2. This value is passed as an argument for the recursive function.
3. The base case for the recursive function is that number should always be greater than 0.
4. If number is greater than 0, function is called again with the argument as the number minus 1.
5. The number is printed.
6. The recursion continues until the number becomes lesser than 0.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter upper limit: 5
1
2
3
4
5
 
Case 2:
Enter upper limit: 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.