Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
Loops repeat a block of code. That way we can keep asking for a guess until the user gets it right, or run a game until it’s over.
A while loop runs while a condition is True:
count = 0
while count < 3:
print("Hello")
count = count + 1
# Prints Hello three times
If the condition never becomes False, the loop runs forever (infinite loop). So we usually change a variable inside the loop so that the condition eventually becomes False.
A for loop runs once for each item in a sequence (e.g. a list or a range):
for i in range(3):
print("Number", i)
# Number 0, Number 1, Number 2
range(5) gives 0, 1, 2, 3, 4. You can use the variable (i here) inside the loop.
Use break to exit the loop immediately:
while True:
answer = input("Type 'quit' to stop: ")
if answer == "quit":
break
print("You said", answer)
The computer picks a random number. The user guesses; the program says “Too high!”, “Too low!” or “Correct!” and keeps asking until they get it.
You’ll need:
import random. Then: secret = random.randint(1, 100) to get a number from 1 to 100.while True: and only break when the guess equals secret.guess to secret and print the right message.Starter code:
import random
secret = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
while True:
guess = int(input("Your guess: "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("Correct! Well done.")
break
Ideas to extend: Count how many guesses they needed. Give a limited number of tries (e.g. 10). Ask if they want to play again (another loop).
Next: 3.1 Lists and arrays — storing multiple values in one variable.