Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

Python Loop Control

Learn break, continue, and loop-else through interactive examples

Learning ModulesInteractive
Choose an interactive example to explore Python loop control flow
Number Guessing Gamebreak
Learn break statements and early loop termination
Attempts: 0/5

Guess a number between 1 and 20!

Guessing Controls
Global Actions
Python Loop Control Code
Live Python code showing break, continue, and loop-else examples
# Python Loop Control - Interactive Examples
# Learn break, continue, and loop-else through hands-on practice
# === NUMBER GUESSING GAME ===
# Example of break statement and early loop termination
target_number = 4
max_attempts = 5
for attempt in range(1, max_attempts + 1):
guess = int(input(f"Attempt {attempt}: Enter your guess (1-20): "))
if guess == target_number:
print(f"Congratulations! You found it in {attempt} attempts!")
break # Exit the loop early when target is found
elif guess < target_number:
print("Too low! Try higher.")
else:
print("Too high! Try lower.")
else:
# This runs only if the loop completes without break
print(f"Game over! The number was {target_number}")
# === PRIME NUMBER FINDER ===
# Example of continue statement and conditional skipping
search_range = 20
primes = []
for num in range(2, search_range + 1):
# Check if number has any factors
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
# Not prime, skip to next number
print(f"{num} is composite (divisible by {factor})")
break
else:
# This runs only if inner loop completed without break
primes.append(num)
print(f"{num} is prime!")
print(f"Found primes: {primes}")
# === SEARCH WITH LOOP-ELSE ===
# Example of loop-else construct
target_item = "apple"
search_list = ["banana", "cherry", "apple", "orange", "grape"]
# Search for the target item
for index, item in enumerate(search_list):
print(f"Checking index {index}: {item}")
if item == target_item:
print(f"Found '"${target_item}"' at index {index}!")
break
else:
# This runs only if the loop completed without finding the item
print(f"'${target_item}' was not found in the list")
print("Searched all items without success")
# === ADVANCED LOOP CONTROL ===
# Example of while True with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input.lower() == 'quit':
print("Goodbye!")
break
if user_input.strip() == ""):
print("Empty input, try again.")
continue # Skip the rest of this iteration
print(f"You entered: {user_input}")
# Key Loop Control Concepts:
# - break: Exit loop immediately
# - continue: Skip to next iteration
# - loop-else: Runs when loop completes naturally (no break)
# - while True: Infinite loop with controlled exit
# - Early termination for efficiency and clean code
History0/5
Recent loop control operations and flow changes

No operations yet

Start by adding or modifying elements