All must be knowing what is a Odd Number in Mathematics.

If the number is not divisible by 2 then the number is called as Odd Number and it’s just the opposite of even number.

In this post we are going to write a program using different methods which will accept a number “n” and will return all the odd numbers between 1 to n.

List Comprehensions – Odd numbers

Method 1: Let’s write the program using List Comprehension Method.
Here the odd_numbers function returns a list of odd numbers between 1 and n(n is inclusive).

I want to return only the odd numbers in a list.

def odd_numbers(n):
	odd_number_list  = [num for num in range(1, n+1) if num % 2 == 1]
	return odd_number_list

print(odd_numbers(6))  
print(odd_numbers(10)) 
print(odd_numbers(11)) 

Here is your output:
[1, 3, 5]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9, 11]

Method 2: Here we are going to write the program using for loop. we need to check if the input number is not divisible by 2. If the number is not divisible by 2, then we have to print it.

# input the number from keyboard
number = int(input("Enter a number: "))

print("\nOdd numbers from 1 to", number, "are : ")

for num in range(1, number + 1):

    #Check if the number is odd or not.
    if((num % 2) != 0):
        print(num," ")

Here is the output:

Enter a number: 3

Odd numbers from 1 to 3 are :
1
3