Print a specific range of numbers in Python

In this article, we will discuss different ways to print a specific range of numbers in Python.

Table Of Contents

Introduction

Suppose we want to print numbers between two specific numbers like 5 & 15. It should print all numbers between them. Like,

5 6 7 8 9 10 11 12 13 14 15

There are different ways to do this. Let’s discuss them one by one,

Method 1: Using range() function

The range() function accepts three arguments,

Advertisements
  • start: The starting number of range
  • end: The last number of range
  • step: The step size or difference between two consecutive numbers in range. Default is 1.

It yields a range of numbers from start till end with the given step size. So, to get a sequence of numbers from 5 to 15, we can pass the start as 5, and end as 15. Use the defult step size i.e. 1. We can also store the returned numbers in a list, and print the list. Let’s see an example,

start = 5
end = 15

# Create a list of numbers from start to end
listOfNum = list(range(start, end+1))

print(*listOfNum)

Output:

5 6 7 8 9 10 11 12 13 14 15

It printed the numbers from 5 to 15.

Method 2: Using List Comprehension

We can create a list of numbers from start to end, by iterating over all the numbers returned by range() function in a list comprehension. It will give us a list of numbers from 5 to 15. Let’s see an example,

start = 5
end = 15

# Create a list of numbers from start to end
listOfNum = [i for i in range(start, end+1)]

print(*listOfNum)

Output:

5 6 7 8 9 10 11 12 13 14 15

It printed the numbers from 5 to 15.

Method 3: Using while loop

To print numbers between start to end, we can iterate from number start till number end using a while loop. During iteration, we can collect all the numbers in a list, and in the end we can print the list contents. Let’s see an example,

start = 5
end = 15

listOfNum = []

i = start
# Iterate over numbers in range
while i <= end:
    # add to list
    listOfNum.append(i)
    i = i+1

# print the numbers in range
print(*listOfNum)

Output:

5 6 7 8 9 10 11 12 13 14 15

It printed the numbers from 5 to 15.

Summary

We learned how to print numbers in specific range in Python. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top