How to write a program to print the odd numbers between two given numbers using a while loop in python.
This program prints all the odd numbers between two given numbers using a while loop in python.
Simple code:
start = int(input("Enter the start number: "))
end = int(input("Enter the end number: "))
while(start <= end):
if(start % 2 != 0):
print(start)
start += 1
Output:
Enter the start number: 1
Enter the end number: 9
1
3
5
7
9
Code with explanation:
# Ask the user to enter the start and end numbers
start = int(input("Enter the start number: "))
end = int(input("Enter the end number: "))
# Use a while loop to iterate through all the numbers between start and end (inclusive)
while(start <= end):
# Check if the current number is odd using the modulus operator
if(start % 2 != 0):
# Print the odd number
print(start)
# Move to the next number
start += 1
Explanation:
- The program prompts the user to enter the start and end numbers using the input() function and stores them in variables ‘start’ and ‘end’.
- A while loop is used to iterate through all the numbers between the start and end (inclusive). At each iteration, the current number is checked if it is odd using the modulus operator. If it is odd, it is printed using the print() function.
- Finally, the loop moves to the next number by incrementing the ‘start’ variable by 1.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.