Zed-King Institute

    Python Program to Print Prime Numbers in a Range

    hardNested loopsPython

    This combines two ideas: a loop over a range of numbers, and the prime check for each one.

    The question

    Read two integers a and b (one per line, a < b) and print every prime number from a to b (both included), separated by spaces.

    The code

    program.py

    a = int(input())
    b = int(input())
    for n in range(max(a, 2), b + 1):
        for i in range(2, int(n ** 0.5) + 1):
            if n % i == 0:
                break
        else:
            print(n, end=" ")
    print()

    Input

    44
    65

    Output

    47 53 59 61

    How it works

    1. 1The outer loop goes through every number n from a to b. max(a, 2) skips 0 and 1, which are not prime.
    2. 2The inner loop tries divisors up to √n and breaks as soon as one divides n.
    3. 3The else of the inner loop runs only when no divisor was found — then n is printed.

    Common mistakes

    • Printing 1 as a prime number.
    • Placing print(n) inside the inner loop, which prints the same number many times.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Nested loops