Programs & Examples
Loops · Study material
All primes up to 50 with for-else
Trial division up to √n; the else of the inner loop runs only when no divisor was found, i.e. when n is prime.
primes = []
for n in range(2, 51):
for d in range(2, int(n ** 0.5) + 1): # trial division up to √n
if n % d == 0:
break
else:
primes.append(n)
print(len(primes), "primes:", *primes)
15 primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Patterns with nested loops
The nested-loops example on the Introduction tab prints a multiplication grid and a centred pyramid of stars.