Book a free demo

Easy ยท ages 10+ ยท nested loops ยท break ยท booleans

Find the prime numbers in Python.

Print every prime number up to 50.

The program

Press Run to see what it prints. Change anything you like, then run it again.

for n in range(2, 51):
    is_prime = True
    for d in range(2, n):
        if n % d == 0:
            is_prime = False
            break
    if is_prime:
        print(n, end=" ")
print()
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

How it works

  1. A prime is a number bigger than 1 whose only factors are 1 and itself.
  2. For each n, the inner loop tries every divisor d. As soon as one divides evenly, n is not prime and break leaves the inner loop.
  3. end=" " keeps everything on one line, separated by spaces.
See the Python path โ†’

Try this

  • Find primes up to 100.
  • Count how many there are.
  • Make the inner loop faster: only try divisors up to the square root of n.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Find the prime numbers: questions

What does the find the prime numbers program do?

Print every prime number up to 50. It prints: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Which Python ideas does it use?

nested loops, break, booleans. Easy level, suitable from about age 10.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Find primes up to 100. Count how many there are. Make the inner loop faster: only try divisors up to the square root of n.

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try