Learn programming concepts interactively
Guess a number between 1 and 20!
# 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 terminationtarget_number = 4max_attempts = 5for 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 foundelif guess < target_number:print("Too low! Try higher.")else:print("Too high! Try lower.")else:# This runs only if the loop completes without breakprint(f"Game over! The number was {target_number}")# === PRIME NUMBER FINDER ===# Example of continue statement and conditional skippingsearch_range = 20primes = []for num in range(2, search_range + 1):# Check if number has any factorsfor factor in range(2, int(num ** 0.5) + 1):if num % factor == 0:# Not prime, skip to next numberprint(f"{num} is composite (divisible by {factor})")breakelse:# This runs only if inner loop completed without breakprimes.append(num)print(f"{num} is prime!")print(f"Found primes: {primes}")# === SEARCH WITH LOOP-ELSE ===# Example of loop-else constructtarget_item = "apple"search_list = ["banana", "cherry", "apple", "orange", "grape"]# Search for the target itemfor index, item in enumerate(search_list):print(f"Checking index {index}: {item}")if item == target_item:print(f"Found '"${target_item}"' at index {index}!")breakelse:# This runs only if the loop completed without finding the itemprint(f"'${target_item}' was not found in the list")print("Searched all items without success")# === ADVANCED LOOP CONTROL ===# Example of while True with breakwhile True:user_input = input("Enter 'quit' to exit: ")if user_input.lower() == 'quit':print("Goodbye!")breakif user_input.strip() == ""):print("Empty input, try again.")continue # Skip the rest of this iterationprint(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
No operations yet
Start by adding or modifying elements