Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

Python Loops

Learn for loops and iteration through interactive examples

Learning ModulesInteractive
Choose an interactive example to explore Python loops and iteration
Pattern Generatorfor/range
Learn for loops and range() with visual pattern creation
Generate a pattern to see the visual output
Pattern Controls
Global Actions
Python Loops Code
Live Python code showing for loop and iteration examples
# Python Loops - Interactive Examples
# Learn for loops, range(), and iteration through hands-on practice
# === PATTERN GENERATOR ===
# Example of nested loops and range() usage
rows = 5
pattern_type = "stars"
if pattern_type == "stars":
for i in range(1, rows + 1):
print("*" * i)
elif pattern_type == "numbers":
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=" ")
print() # New line
elif pattern_type == "pyramid":
for i in range(1, rows + 1):
spaces = " " * (rows - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)
# === DATA PROCESSOR ===
# Example of list comprehensions and iteration
input_data = [1, 2, 3, 4, 5]
operation = "double"
if operation == "double":
result = [x * 2 for x in input_data]
elif operation == "square":
result = [x ** 2 for x in input_data]
elif operation == "filter_even":
result = [x for x in input_data if x % 2 == 0]
elif operation == "sum":
total = 0
for number in input_data:
total += number
result = total
print(f"Operation: {operation}")
print(f"Input: {input_data}")
print(f"Result: {result}")
# === SHOPPING CART CALCULATOR ===
# Example of iterating through complex data structures
shopping_cart = [
{"name": "Laptop", "price": 999.99, "quantity": 1},
{"name": "Mouse", "price": 29.99, "quantity": 2},
{"name": "Keyboard", "price": 79.99, "quantity": 1}
]
# Calculate subtotal
subtotal = 0
for item in shopping_cart:
item_total = item["price"] * item["quantity"]
subtotal += item_total
print(f"{item['name']}: ${item['price']:.2f} x {item['quantity']} = ${item_total:.2f}")
# Apply discount if subtotal > $500
discount = subtotal * 0.1 if subtotal > 500 else 0
total = subtotal - discount
print(f"\nSubtotal: ${subtotal:.2f}")
print(f"Discount: ${discount:.2f}")
print(f"Total: ${total:.2f}")
# Key Loop Concepts:
# - for loops with range(start, stop, step)
# - Iterating through lists, strings, and dictionaries
# - List comprehensions for concise transformations
# - Nested loops for complex patterns
# - enumerate() for index and value pairs
# - Breaking down complex problems into iterations
History0/5
Recent loop operations and transformations

No operations yet

Start by adding or modifying elements