Python loops practice for while VS Code real programs

Python loops practice — 3 programs that finally make sense

In the previous article we covered Python loops theory. Now it’s time to write real code.

In this article we build three programs from scratch in VS Code using for and while in situations where the choice between them isn’t arbitrary, each program uses the loop that genuinely makes more sense for that problem.

Create a folder called loops_practice and a separate file for each program.

Python loops practice — Program 1: Password validator

This program asks for a password and keeps asking until the user enters one that meets all the requirements. It’s a perfect while use case — we don’t know how many attempts the user will need.

Create the file password_validator.py:

# Password validator with while loop
import string

print("=== PASSWORD VALIDATOR ===\n")
print("Requirements:")
print("  - At least 8 characters")
print("  - At least one uppercase letter")
print("  - At least one lowercase letter")
print("  - At least one number")
print("  - At least one special character (!@#$%^&*)\n")

specials = "!@#$%^&*"
valid = False
attempts = 0

while not valid:
    password = input("Enter password: ")
    attempts += 1
    errors = []

    # Check each requirement
    if len(password) < 8:
        errors.append("Too short (minimum 8 characters)")
    if not any(c.isupper() for c in password):
        errors.append("No uppercase letters")
    if not any(c.islower() for c in password):
        errors.append("No lowercase letters")
    if not any(c.isdigit() for c in password):
        errors.append("No numbers")
    if not any(c in specials for c in password):
        errors.append("No special characters")

    if errors:
        print(f"\n✗ Invalid password ({len(errors)} error(s)):")
        for error in errors:
            print(f"  - {error}")
        print()
    else:
        valid = True

print(f"\n✓ Valid password accepted in {attempts} attempt(s)")
print(f"Password strength: {'Strong' if len(password) >= 12 else 'Acceptable'}")

Output:

=== PASSWORD VALIDATOR ===

Requirements:
  - At least 8 characters
  ...

Enter password: hello
✗ Invalid password (4 errors):
  - Too short (minimum 8 characters)
  - No uppercase letters
  - No numbers
  - No special characters

Enter password: Python@2024
✓ Valid password accepted in 2 attempt(s)
Password strength: Strong

Why while and not for? Because we don’t know how many attempts the user will need. If they get it right on the first try the loop runs once. If they make five mistakes it runs six times. The for loop needs a fixed number of iterations, while doesn’t.

Notice the errors list inside the loop, it resets to empty at the start of each iteration, so errors from the previous attempt don’t carry over. This is a very common pattern in validation loops.

Python loops practice — Program 2: Factorial calculator

The factorial of a number n (written n!) is the product of all positive integers from 1 to n. So 5! = 5 × 4 × 3 × 2 × 1 = 120.

Create the file factorial.py. This is a perfect for case, we know exactly how many multiplications to do:

# Factorial calculator — for vs while comparison
print("=== FACTORIAL CALCULATOR ===\n")

n = int(input("Enter a positive integer: "))

if n < 0:
    print("Error: factorial is only defined for non-negative integers")
elif n == 0:
    print("0! = 1  (by definition)")
else:
    # Version with for loop
    factorial_for = 1
    steps_for = []

    for i in range(1, n + 1):
        factorial_for *= i
        steps_for.append(str(i))

    print(f"\n--- Using for loop ---")
    print(f"{n}! = {' × '.join(steps_for)} = {factorial_for}")

    # Same result using while loop
    factorial_while = 1
    i = 1
    steps_while = []

    while i <= n:
        factorial_while *= i
        steps_while.append(str(i))
        i += 1

    print(f"\n--- Using while loop ---")
    print(f"{n}! = {' × '.join(steps_while)} = {factorial_while}")

    print(f"\nBoth give the same result: {factorial_for}")
    print(f"\nWhy for is better here:")
    print(f"  for   → 'repeat exactly {n} times' — clear and direct")
    print(f"  while → needs manual counter (i = 1, i += 1) — more error-prone")

Output with n = 5:

=== FACTORIAL CALCULATOR ===

Enter a positive integer: 5

--- Using for loop ---
5! = 1 × 2 × 3 × 4 × 5 = 120

--- Using while loop ---
5! = 1 × 2 × 3 × 4 × 5 = 120

Both give the same result: 120

Why for is better here:
  for   → 'repeat exactly 5 times' — clear and direct
  while → needs manual counter (i = 1, i += 1) — more error-prone

Both loops give the same result, but for is cleaner because the number of iterations is fixed and known. This is the key insight of the program: both loops can solve the same problem, but one is always more natural than the other depending on the situation.

The steps list that stores each factor is a nice touch, it lets us show the complete calculation 1 × 2 × 3 × 4 × 5 using ' × '.join(steps). This is string joining combined with a list built inside a loop, a pattern you’ll use often.

Python loops practice — Program 3: Countdown with launch sequence

The most visual of the three. Create the file countdown.py:

# Countdown with launch sequence
import time    # to add pauses between numbers

print("=== LAUNCH COUNTDOWN ===\n")

mission = input("Mission name: ")
seconds = int(input("Countdown from (seconds): "))

if seconds <= 0:
    print("Error: countdown must be a positive number")
else:
    print(f"\nMission: {mission}")
    print("Starting countdown...\n")

    # Main countdown — for in reverse
    for i in range(seconds, 0, -1):
        if i > 10:
            print(f"  T-{i:3d}s")
        elif i > 3:
            print(f"  T-{i:3d}s  ⚡")
        else:
            print(f"  T-{i:3d}s  🔴 CRITICAL")

        # time.sleep(1)  # uncomment to add real pauses

    print("\n  🚀 LIFTOFF! All systems go!")
    print(f"\n  Mission '{mission}' launched successfully")

    # Mission statistics using while
    print("\n--- Mission log ---")
    phase = 1
    altitude = 0
    fuel = 100.0
    t = 0

    while fuel > 0 and altitude < 1000:
        altitude += 50 * phase
        fuel -= 8.5 + phase * 1.2
        t += 1

        if t <= 3 or altitude >= 950:
            print(f"  T+{t:02d}s | Altitude: {altitude:4d}m | Fuel: {max(0, round(fuel, 1)):5.1f}%")

        if altitude >= 500 and phase == 1:
            phase = 2
            print(f"  → Phase 2 engaged at T+{t}s")

    print(f"\n  Simulation complete — {t} seconds elapsed")
    print(f"  Final altitude: {min(altitude, 1000)}m")
    print(f"  Fuel remaining: {max(0, round(fuel, 1))}%")

Output with mission “Apollo” and 5 seconds:

=== LAUNCH COUNTDOWN ===

Mission name: Apollo
Countdown from (seconds): 5

Mission: Apollo
Starting countdown...

  T-  5s  ⚡
  T-  4s  ⚡
  T-  3s  🔴 CRITICAL
  T-  2s  🔴 CRITICAL
  T-  1s  🔴 CRITICAL

  🚀 LIFTOFF! All systems go!

  Mission 'Apollo' launched successfully

--- Mission log ---
  T+01s | Altitude:   50m | Fuel:  90.3%
  T+02s | Altitude:  100m | Fuel:  79.7%
  T+03s | Altitude:  150m | Fuel:  69.0%
  → Phase 2 engaged at T+10s
  T+14s | Altitude: 1000m | Fuel:   2.1%

  Simulation complete — 14 seconds elapsed
  Final altitude: 1000m
  Fuel remaining: 2.1%

This program uses for and while for different purposes in the same code. The countdown uses for with range(seconds, 0, -1) — a reversed range, because we know exactly how many seconds. The mission simulation uses while because we don’t know when the fuel will run out or when the altitude target will be reached, both are conditions that evolve.

for vs while — the comparison that makes it click

After writing these three programs the difference should be clear. Here it is in one table:

                    for                     while
─────────────────────────────────────────────────────
When to use    Known repetitions      Unknown repetitions
Control        Sequence/range         Condition
Counter        Automatic              Manual (you update it)
Risk           Low                    Infinite loop if condition never False
Classic use    Factorial, tables,     Validation, games,
               lists, patterns        search, menus
Example        for i in range(10)     while not valid:

The golden question to ask yourself before choosing: “do I know how many times this needs to repeat?” If yes → for. If no → while.

Visualise it with Python Tutor

Paste the factorial program with n = 4 into pythontutor.com (select Python 3). Step through both versions, the for and the while, and compare them side by side in your head. You’ll see how for handles the counter automatically (the i in range(1, 5) advances on its own) while while requires you to manually write i += 1. Both produce the same result but the for has one less thing to forget.

Summary and next step

In this article you practised Python loops with three real programs. You used while for validation (unknown attempts), for for factorial (known iterations) and both together in the countdown simulation. You saw a reversed range(), the accumulator pattern inside loops, list building with loops, and the conditions that make each loop the right choice.

In the next article in this series you’ll find proposed exercises with solutions to practice on your own.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *