Python Program to Print Odd Numbers from 1 to n. One of the fundamental concepts in programming is how to manipulate and iterate through number sequences. A common exercise is creating a program to print odd numbers within in a specified range. This article will guide you through writing a Python program to print odd numbers from 1 to the given number n.
Table of Contents
How to Print Odd Numbers from 1 to n in Python
There are several methods available for this purpose. Here we are going to explore two methods to achieve this.
Uisng a For Loop
The for loop in Python allows us to iterate over a sequence of numbers. Here is how you can use it to print odd numbers-
# Getting the upper limit from user
n = int(input("Enter the upper limit "))
# Using the for loop to iterate from 1 to n
for i in range(1,n+1):
# checking if the number is odd
if i%2 != 0:
print(i)
This program works by iterating through each number from 1 to n, checking if the number is odd by using the modulus operator ‘%’ and printing it if true.
Using List Comprehension
List comprehension offers a more concise way to achieve the same result. It is a compact way to process elements and return a list.
# Getting the upper limit from user
n = int(input("Enter the upper limit "))
# using list comprehension to find odd numbers
odd_numbers = [i for i in range(1,n+1) if i%2 !=0]
print(odd_numbers)
In this method, We create a list of odd numbers by iterating through the range and checking the odd condition in a single line.
Printing odd numbers using Python demonstrates the basic use of loops or conditional statement-core concepts in any programming language.
Happy Coding & Learning
1 thought on “Python Program to Print Odd Numbers from 1 to n”