← Back to Blog

while loops — The Full Picture

The idea!

You've covered random, while, complex conditions, while True, while + random, and while...else.

This is your reference. Everything in one place.

Come back here whenever you need a reminder.

random

import random

random.randint(1, 6)       # random integer — both ends included
random.choice("Bull")      # random item from a sequence

while — the basic loop

count = 0

while count < 5:
    print(count)
    count += 1    # always update — or it runs forever

Runs as long as the condition is True. You control what changes inside.

while with and / or / not

while answer != password and attempts < 3:
    # both must be True to keep looping

while health > 0 or ammo > 0:
    # at least one must be True

while not done:
    # runs while done is False

while True + break

while True:
    entry = input("Enter a number (or 'stop'): ")
    if entry == "stop":
        break
    total += int(entry)

Runs forever. break is the only exit. Use when the exit condition lives inside the loop.

while + random

import random

roll = 0
attempts = 0

while roll != 6:
    roll = random.randint(1, 6)
    attempts += 1

print(f"Got 6 after {attempts} attempt(s).")

Generate inside the loop — fresh each iteration. Counter tracks attempts.

while...else

while attempts < 3:
    guess = int(input("Guess (1-5): "))
    attempts += 1
    if guess == secret:
        print("Correct!")
        break
else:
    print(f"Out of attempts. The number was {secret}.")

else runs when condition becomes False naturally. Skipped when break fires.

Common Mistakes

  • Always update something inside — or loop runs forever
  • Check the condition before the loop — it might never run
  • Every while True needs a reachable break
  • Validate input before int() — crashes on words
  • < vs <= — know which boundary you want
  • else is skipped when break fires

What you should understand now

  • while repeats as long as a condition is True — you control what changes
  • and, or, not combine conditions — same rules as if
  • while True + break — infinite loop, controlled exit
  • random inside while — unpredictable length, predictable structure
  • while...else — completed or interrupted, while knows the difference
[ login to bookmark ] // copied! 20 views · 1 min
// resources
Cheatsheet while loops — The Full Picture
← prev Common WHILE Mistakes next → This One's Yours — WHILE
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.