Roll until you win
The problem...
You've used random. You've used while. Separately, they're useful.
Together — they become something different. A loop that runs until luck decides to stop it.
You don't control how many iterations. You don't know when it ends. That's exactly the point.
The idea!
Generate a random value on every iteration. Check it against a condition. Keep going until the condition is met.
The loop runs as long as the target hasn't been hit. Random decides when that happens.
Roll until you hit 6
import random
roll = 0
attempts = 0
while roll != 6:
roll = random.randint(1, 6)
attempts += 1
print(f"Rolled: {roll}")
print(f"Got 6 after {attempts} attempt(s).")
# Rolled: 3
# Rolled: 1
# Rolled: 5
# Rolled: 6
# Got 6 after 4 attempt(s).
Every run is different. Every run ends eventually. Random decides when — you just set the target.
Counting attempts
The counter outside the loop tracks how many times it took. Same pattern as always — define before, update inside, use after.
while True + random
import random
print("Searching for the lucky number...")
while True:
number = random.randint(1, 100)
if number == 42:
print(f"Found it: {number}")
break
print(f"Not yet: {number}")
The loop runs until it randomly lands on 42. Could be 3 iterations. Could be 300. You genuinely don't know.
A real example — guessing game setup
import random
secret = random.randint(1, 10)
guess = 0
attempts = 0
while guess != secret:
guess = int(input("Guess a number (1-10): "))
attempts += 1
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
print(f"Correct! Got it in {attempts} attempt(s).")
Random sets the secret. The user guesses. The loop runs until they're right. Neither you nor the user knows how long that takes.
Heads up!
- Generate the random value inside the loop — not before it
- The counter goes outside — define before, update inside
while True+breakworks well when the exit condition is inside the logic- Every run gives different results — test it multiple times
The mindset shift
Stop thinking: "I need to know how many times the loop runs."
Start thinking: "The loop runs until the condition is met — random decides when."
What you should understand now
while+randomcreates loops with unpredictable length- Generate the random value inside the loop — fresh each iteration
- A counter tracks attempts — define before, update inside, use after
- The guessing game pattern is one of the most common uses of
while+random