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
- A prime is a number bigger than 1 whose only factors are 1 and itself.
- For each
n, the inner loop tries every divisord. As soon as one divides evenly,nis not prime andbreakleaves the inner loop. end=" "keeps everything on one line, separated by spaces.
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
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
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.
Pick a game
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay