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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...