// Control Flow
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 Trueneeds a reachablebreak - Validate input before
int()— crashes on words <vs<=— know which boundary you wantelseis skipped whenbreakfires
What you should understand now
whilerepeats as long as a condition is True — you control what changesand,or,notcombine conditions — same rules asifwhile True+break— infinite loop, controlled exitrandominsidewhile— unpredictable length, predictable structurewhile...else— completed or interrupted,whileknows the difference
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment