- Task: print all prime numbers between 1 and 100 (2, 3, 5, 7, 11, 13, ...).
- You already know how to check one number: count factors; if count == 2, it's prime.
- Idea: loop
nfrom 1 to 100; for eachn, do the prime check; if prime, printn. - So "prime check" is inside an outer loop over
n.
Letβs go! π
Part 1: Recall β How to Check One Number
π For a single number n:
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == 2:
# n is prime (only factors 1 and n)
Part 2: From 1 to 100 β Add an Outer Loop
π We want to check every n from 1 to 100. So we put the whole prime-check inside:
for n in range(1, 101): # 1 to 100 inclusive
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == 2:
print(n)
range(1, 101) gives 1, 2, 3, ..., 100. For each n we count factors; if count is 2, we print n.
Part 3: Demo β Primes from 1 to 30 (Short)
Primes from 1 to 30:
for n in range(1, 31):
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == 2:
print(f" {n}", end=" ")
Output:
2 3 5 7 11 13 17 19 23 29
Part 4: Summary
β
Outer loop: n from 1 to 100 β for n in range(1, 101)
β Inner logic: same as single prime check (count factors; if count == 2, prime).
β
If prime: print(n). No need to print not-prime for other numbers.
Congratulations! You now understand how to Print Prime Numbers from 1 to 100 in Python! π
Key Takeaways:
- Reuse your single-number prime check inside an outer
forloop range(1, 101)covers 1 to 100- Total work: 100 outer loops Γ (average ~50 inner checks)
- This is the foundation for any range-based prime finder
Next Steps:
- Make it faster: check only up to βn (weβll learn optimization soon)
- Add user input (ask for range 1 to N)
- Print primes in a nice table or list