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:
- The program defines a function called
print_odd_numbers
that takes two parameters:start
andend
. - Inside the function, a
for
loop is used to iterate through each number in the range fromstart
toend + 1
. The+1
is added to include theend
number in the range. - 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. - If the number is odd, it is printed using the
print
statement. - In the main program, the user is prompted to enter the starting and ending numbers of the range.
- The
print_odd_numbers
function is called with thestart
andend
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