🐍

Loops: Repeating Code

Beginner
90 XP
40 min
Lesson Content

Loops: Automating Repetition

Loops allow you to repeat code multiple times. This is essential for processing data, iterating through collections, and automating tasks.

The for Loop

Iterate over a sequence (list, string, range, etc.):

# Loop through a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

# Loop through a string
for char in "Python":
print(char)

# Loop with range()
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4

The range() Function

Generate a sequence of numbers:

# range(stop) - 0 to stop-1
range(5) # 0, 1, 2, 3, 4

# range(start, stop) - start to stop-1
range(2, 6) # 2, 3, 4, 5

# range(start, stop, step) - with step size
range(0, 10, 2) # 0, 2, 4, 6, 8
range(10, 0, -1) # 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

The while Loop

Repeat while a condition is True:

# Count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1

# User input loop
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")

Loop Control: break and continue

Control the flow of loops:

# break - exit the loop immediately
for i in range(10):
if i == 5:
break # Exit when i is 5
print(i) # Prints 0, 1, 2, 3, 4

# continue - skip to next iteration
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints 1, 3, 5, 7, 9

Nested Loops

Loops inside loops:

# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")

Common Loop Patterns

# Sum numbers from 1 to 10
total = 0
for i in range(1, 11):
total += i
print(f"Sum: {total}") # Sum: 55

# Find maximum in a list
numbers = [3, 7, 2, 9, 1]
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print(f"Maximum: {maximum}") # Maximum: 9

for vs while

  • for: Use when you know how many times to loop
  • while: Use when you need to loop until a condition changes
Example Code

Use loops to create number patterns.

# Print numbers from 1 to 10
for i in range(1, 11):
    print(i)

# Print even numbers from 2 to 20
for i in range(2, 21, 2):
    print(i)

Expected Output:

1
2
3
4
5
6
7
8
9
10
2
4
6
8
10
12
14
16
18
20
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code