Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to print numbers from N to 1 - Python Program

Example 1 :

def print_n_to_1(n): """Print numbers from n to 1 recursively.""" if n == 0: return print(n) print_n_to_1(n-1) print_n_to_1(5)

Output

 
OUTPUT  :
5
4
3
2
1
 

Example 2 : Advanced Program

def print_n_to_1(n): """ Recursively prints numbers from n down to 1. Args: n: The starting integer. """ # Base case: When n becomes 0 or less, stop the recursion. if n <= 0: return # Print the current value of n print(n) # Recursive call: Call the function with n-1 print_n_to_1(n - 1) # Example Usage: N = int(input("Enter a number : ")) print(f"Printing numbers from {N} to 1:") print_n_to_1(N)

Output

 
OUTPUT  :
Enter a number  : 5
Printing numbers from 5 to 1:
5
4
3
2
1