Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Print All Odd Numbers in a Range

# Python Program to Print All Odd Numbers in a Range

In this Python program, we will print all the odd numbers within a given range. We will use a loop to iterate through the numbers in the range and check if each number is odd. If a number is odd, it will be printed.

## Problem Statement:

Write a Python program to print all the odd numbers within a given range.

## Python Program to Print All Odd Numbers in a Range:

``````def print_odd_numbers(start, end):
for num in range(start, end + 1):
if num % 2 != 0:
print(num)

# Main program
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
print(f"All odd numbers between {start} and {end}:")
print_odd_numbers(start, end)
``````

## How it Works:

1. The program defines a function called `print_odd_numbers` that takes two parameters: `start` and `end`.
2. Inside the function, a `for` loop is used to iterate through each number in the range from `start` to `end + 1`. The `+1` is added to include the `end` number in the range.
3. For each number in the range, it checks if the number is odd by using the modulus operator `%`. If the remainder of dividing the number by 2 is not equal to 0, it means the number is odd.
4. If the number is odd, it is printed using the `print` statement.
5. In the main program, the user is prompted to enter the starting and ending numbers of the range.
6. The `print_odd_numbers` function is called with the `start` and `end` values as arguments, which will print all the odd numbers within the given range.

## Input/Output:

``````Enter the starting number: 1
Enter the ending number: 10
All odd numbers between 1 and 10:
1
3
5
7
9

Enter the starting number: 15
Enter the ending number: 25
All odd numbers between 15 and 25:
15
17
19
21
23
25
``````

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...