Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 7 of 14
print-primes-between-1-100.py
1# Print primes from 1 to 100
2print("Prime numbers from 1 to 100:")
3for num in range(2, 101):
4 is_prime = True
5 for i in range(2, int(num ** 0.5) + 1):
6 if num % i == 0:
7 is_prime = False
8 break
9 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. 1

    Visit candidates two through one hundred.

  2. 2

    Clear the candidate flag on its first found factor.

  3. 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.