How to Print all Prime Numbers within a Range in Python


In this example we will show how to print all prime numbers in a given range. In Python, it can be implemented through loops and judgment statements to select the prime numbers within the range.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

lowerLimit = int(input("Please input the lower limit: "))
upperLimit = int(input("Please input the upper limit: "))
print("Primer between {} and {} are: ".format(lowerLimit, upperLimit))
for i in range(lowerLimit, upperLimit + 1):
    k = 0
    for j in range(1, i+1):
        if i % j == 0:
            k = k + 1
    if k == 2:
        print(str(i) + "\t", sep=" ", end=" ")

Output:

Please input the lower limit: 1
Please input the upper limit: 10
Primer between 1 and 10 are: 
2	 3	 5	 7

Please input the lower limit: 3
Please input the upper limit: 30
Primer between 3 and 30 are: 
3	 5	 7	 11	 13	 17	 19	 23	 29
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments