Loops Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Consolidate your loops mastery by solving standard placement technical coding round problems.
Prime number check with for-else
Prime number is a whole number greater than 1 that has no divisors other than 1 and itself.
A number is prime if it has no divisors other than 1 and itself. We only need to test divisors up to √N.
n = 29if n < 2: print(f"{n} is not prime")else: for d in range(2, int(n ** 0.5) + 1): if n % d == 0: print(f"{n} is not prime") break else: print(f"{n} is prime")Because no divisor between 2 and 5 evenly divides 29, the loop finishes without breaking and the else block executes.
Mathematical digit reversal
Digit extraction splits a number into its digits with two operations: n % 10 gives the last digit and n // 10 removes it.
Extract the last digit using % 10 and strip it using // 10 in a while loop to reverse a number without string conversions.
num = 1234rev = 0while num > 0: rev = (rev * 10) + (num % 10) num //= 10print(f"Reversed: {rev}")Example 1 · Is 121 a palindrome?
num = 121original = numrev = 0while num > 0: rev = rev * 10 + num % 10 num //= 10if rev == original: print(f"{original} is a palindrome")else: print(f"{original} is not a palindrome")121 is a palindrome
What this code does
- A palindrome number reads the same from both ends, so its reverse equals the number.
originalkeeps the number, because the loop usesnumup until it is 0.- The reverse of 121 is 121, so the
ifbranch runs.
The loop mathematically extracts 4, 3, 2, 1, building 4321 in O(log10 N) time.
Example 2 · Factorial of 5
n = 5fact = 1for i in range(2, n + 1): fact *= iprint(f"{n}! = {fact}")5! = 120
What this code does
factstarts at 1, because starting at 0 would make every product 0.- The loop multiplies by 2, 3, 4 and 5, which gives 120.
Example 3 · Fibonacci series
n_terms = 5a, b = 0, 1
print("Fibonacci:", end="")for _ in range(n_terms): print(f" {a}", end="") a, b = b, a + bprint()Fibonacci: 0 1 1 2 3
What this code does
- Uses tuple swapping
a, b = b, a + bon each iteration. - Prints the first 5 Fibonacci numbers on one line: 0, 1, 1, 2, 3.
Finish up
Mark complete & continue
Next: Must-do problems: Loops