Open In App

Print Numbers in an Interval – Python

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn how to print numbers within a given interval in Python using simple loops, list comprehensions, and step-based ranges.

For Example:

Input : i = 2, j = 5
Output : 2 3 4 5

Input : i = 10, j = 20 , s = 2
Output : 10 12 14 16 18 20

Let’s explore different methods to print numbers between two values in Python.

Print All Numbers Between Two Values

The simplest way to print numbers in an interval is by using a for loop with the range() function.

Python
i = 10
j = 20

for num in range(i, j + 1):
    print(num)

Output
10
11
12
13
14
15
16
17
18
19
20

Explanation:

  • range(i, j + 1) includes the upper limit by adding +1.
  • loop prints each number from i to j one by one.

Print Only Even Numbers in an Interval

You can modify the step of the range() function to skip numbers, such as printing only even numbers.

Python
i = 10
j = 20

if i % 2 == 0:
    for num in range(i, j + 1, 2):
        print(num)
else:
    for num in range(i + 1, j + 1, 2):
        print(num)

Output
10
12
14
16
18
20

Explanation:

  • code ensures that the loop starts with the first even number in the interval.
  • range(…, …, 2) increases the count by 2 to skip odd numbers.

Generate Numbers Using List Comprehension

List comprehensions offer a short and elegant way to generate a list of numbers within a given range.

Python
i = 10
j = 20
a = [num for num in range(i, j + 1)]
print(a)

Output
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Explanation:

  • [num for num in range(l, u + 1)] builds a list of numbers from l to u.
  • final result is printed as a list.

For in-depth knowledge of the methods used in this article, read: for-loops, list comprehension, range(), Python.



Next Article
Article Tags :
Practice Tags :

Similar Reads