How to print 1 to n using recursion in Python
Overview
Recursion is a very common concept in all programming languages. It means a function can call itself repeatedly until it finds a terminating condition.
In this shot, we’ll see how to print 1 to n using recursion.
Algorithm
Let’s go through the approach to solving this problem first.
- We define a function that accepts a number
n. - We recursively call the function and print the value of
n, until the value ofnis greater than0.
Example
The code snippet below demonstrates how to print 1 to n using recursion.
# python3 program to print 1 to n using recursiondef printNumber(n):# check if n is greater than 0if n > 0:# recursively call the printNumber functionprintNumber(n - 1)# print nprint(n, end = ' ')# declare the value of nn = 50# call the printNumber functionprintNumber(n)
Explanation
- Line 3: We define a function
printNumber()that accepts a parametern. - Line 5: We check if the value of
nis greater than0. - Lines 7–9: If the above condition is
true, we recursively call the functionprintNumber()withn - 1, and print the value ofnon the console. We use theendattribute inprint()function to format the output. - Line 12: We declare and initialize a variable
n. - Line 14: We call the function
printNumber()and passnas an argument.
Output
In the output, we can see all the numbers between 1 and n are separated by spaces.