Print Primes Between 1-100
List primes from two through one hundred with nested loops. Students trace a fresh candidate flag, square-root bounds, and early exit after finding a factor.
1# Print primes from 1 to 1002print("Prime numbers from 1 to 100:")3for num in range(2, 101):4 is_prime = True5 for i in range(2, int(num ** 0.5) + 1):6 if num % i == 0:7 is_prime = False8 break9 if is_prime:10 print(num, end=" ")11print()
Output
Prime numbers from 1 to 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
In this one
- Separate candidate and divisor loops
- Reset a prime flag
- Use a square-root bound
How it works
- 1
Visit candidates two through one hundred.
- 2
Clear the candidate flag on its first found factor.
- 3
Print only candidates whose flags remain true.
Edge cases
Why include a square-root endpoint?
Why include a square-root endpoint?
A square such as 49 has its factor seven there.
Does the inner break end the whole search?
Does the inner break end the whole search?
No. The outer loop continues with the next candidate.
What's going on
Each outer-loop value gets a new is_prime flag. The inner loop tries possible divisors only up to the square root, including that endpoint when it is an integer.
A factor sets the flag false and breaks only the inner loop. Candidates still marked true print on the same line. Starting at two avoids incorrectly treating one as prime, and resetting the flag prevents a composite from affecting later candidates.
Why include a square-root endpoint? A square such as 49 has its factor seven there.
Does the inner break end the whole search? No. The outer loop continues with the next candidate.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why reset is_prime each time?
Pick an answer to check it.
Question 2
Why include a square-root endpoint?
Pick an answer to check it.
Questions people ask
Why include a square-root endpoint?
A square such as 49 has its factor seven there.
Does the inner break end the whole search?
No. The outer loop continues with the next candidate.
Why reset is_prime each time?
Each candidate needs its own decision.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum