Python Program to Print Odd Numbers in a Range

1. Introduction

Printing odd numbers within a given range is a common task that can be accomplished in various ways in Python. In this blog post, we will utilize recursion to print all odd numbers within a range. 

Recursion is a programming concept where a function calls itself with a modified parameter until a base case is reached. In our task, the base case will be when the start of the range is greater than the end.

2. Program Steps

1. Define a recursive function to print odd numbers within a range.

2. Check if the start number is greater than the end number (base case).

3. If the current number is odd, print it.

4. Recursively call the function with the next number in the range.

3. Code Program

def print_odd_numbers(start, end):
    # Base case: if the start is greater than end, stop the recursion
    if start > end:
        return
    # Check if the current number is odd
    if start % 2 != 0:
        print(start)
    # Recursively call the function with the next number
    print_odd_numbers(start + 1, end)

Output:

print_odd_numbers(1, 10)
# Output:
1
3
5
7
9

Explanation:

1. A function named print_odd_numbers is defined with two parameters, start and end.

2. The function first checks if start is greater than end. If so, it returns, acting as the base case to stop recursion.

3. If start is not greater than end, the function checks if start is odd by using the modulus operator (start % 2 != 0). If this condition is true, it prints start.

4. The function then calls itself with start + 1 and end as arguments, effectively moving to the next number in the range.

5. This process repeats until the base case is met, at which point the function stops calling itself, and all odd numbers in the range have been printed.

Comments