How to Print Odd Numbers in Python using Range

How to Print Odd Numbers in Python using Range | The problem is to print the odd numbers in the given range. We can do this by three methods and also by using the range() method available in Python. 

The limits of range you can take from the end-user or you can also specify in the code directly. The range function in python helps to define the limit. 

Method declaration:- range(start, stop, step)

Start:- This is an integer specifying at which position to start this is an optional field. The default value is 1.
Stop:-
This is an integer value specifying at which position to stop this field is required. This is an optional field the default value is 1.
Step:- This indicates the increment, this is also an optional field.

Example to demonstrate range() function:-

a = range(8)
This code just returns the integer elements from 0 to 8.

a = range(1,7)
This code returns a value from 1 to 7.

a = range(3,5,2)
This returns the integer value from 3 to 5 with an increment of 2.

low, end = 4, 19
for i in range(low, end + 1):
   if i % 2 != 0:
      print(i, end = " ")

Output:

5 7 9 11 13 15 17 19

low = int(input("Enter the lower limit for the range: "))
end = int(input("Enter the upper limit for the range: "))
for i in range(low, end + 1):
   if i % 2 != 0:
      print(i, end = " ")

Output:-

Enter the lower limit for the range: 3
Enter the upper limit for the range: 9
3 5 7 9

Enter the lower limit for the range: 10
Enter the upper limit for the range: 30
11 13 15 17 19 21 23 25 27 29

In the above program, we have used the input() method to take the input from the end-user. The input is converted to an integer value using the int() method. We have taken “low” and “end” points for the range.

Using for loop we have iterated the range and checked whether the number is odd or not. If it an odd number then we display them.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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