Python Tutorials

Python Programs

Python Print all Prime Numbers in an Interval


Python Print all Prime Numbers in an Interval

In this tutorial, we will learn how to print all prime numbers in a given interval in Python. We will cover the basic logic and conditions required to find prime numbers within a specified range.


What is a Prime Number

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This means that a prime number cannot be formed by multiplying two smaller natural numbers.


Syntax

The syntax to find and print all prime numbers in an interval in Python is:

def is_prime(number):
    if number <= 1:
        return False
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False
    return True

for num in range(start, end + 1):
    if is_prime(num):
        print(num)


Printing all prime numbers in an interval

We can create a function to check if a number is prime and use it to find and print all prime numbers within a specified range.

For example,

  1. Define a function named is_prime that takes one parameter number.
  2. Check if the number is less than or equal to 1. If true, return False.
  3. Use a for loop to iterate from 2 to the square root of the number (inclusive).
  4. Check if the number is divisible by any of the values in the loop. If true, return False.
  5. If the loop completes without finding any divisors, return True.
  6. Declare the start and end values for the interval.
  7. Use a for loop to iterate through the numbers in the interval.
  8. Use the is_prime function to check if the current number is prime. If true, print the number.

Python Program

def is_prime(number):
    if number <= 1:
        return False
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False
    return True

# Define the interval
start = 10
end = 50

# Print all prime numbers in the interval
for num in range(start, end + 1):
    if is_prime(num):
        print(num)

Output

11
13
17
19
23
29
31
37
41
43
47