Loops: Repeating Actions
Use for and while loops to repeat code without writing it multiple times.
Prerequisites
Loops let you repeat code. Instead of writing the same thing 100 times, you write it once and tell Python how many times to repeat it.
The for Loop
A for loop repeats code for each item in a sequence:
# Print numbers 0 through 4
for i in range(5):
print(i)Output:
0
1
2
3
4range(5) generates numbers 0, 1, 2, 3, 4 (five numbers, starting from 0). The variable i takes each value in turn.
range() Options
# range(stop) - 0 to stop-1
for i in range(3):
print(i) # 0, 1, 2
# range(start, stop) - start to stop-1
for i in range(2, 5):
print(i) # 2, 3, 4
# range(start, stop, step) - with custom increment
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Counting backwards
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1Looping Over Lists
You can loop directly over items in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")Output:
I like apple
I like banana
I like cherryLooping Over Strings
word = "Python"
for letter in word:
print(letter)Output: P, y, t, h, o, n (each on its own line)
The while Loop
A while loop repeats as long as a condition is True:
count = 0
while count < 5:
print(count)
count += 1 # Don't forget this or it loops forever!
print("Done!")Output: 0, 1, 2, 3, 4, Done!
break and continue
break exits the loop immediately. continue skips to the next iteration:
# break - exit the loop early
for i in range(10):
if i == 5:
break # Stop when we hit 5
print(i) # Prints 0, 1, 2, 3, 4
# continue - skip this iteration
for i in range(5):
if i == 2:
continue # Skip 2
print(i) # Prints 0, 1, 3, 4Practical Example: Sum and Average
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print(f"Sum: {total}") # Sum: 150
print(f"Average: {average}") # Average: 30.0Nested 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}")
print("---") # Separator after each rowPractice
- Print all even numbers from 1 to 20
- Calculate the factorial of a number (5! = 5 * 4 * 3 * 2 * 1)
- Print a countdown from 10 to 1, then print "Liftoff!"
- Find the largest number in a list without using max()
- Print a triangle of stars (first row has 1, second has 2, etc.)
Making Decisions with If/Else
Control the flow of your program by making decisions based on conditions.
Functions: Reusable Code
Package code into reusable functions. Understand parameters, return values, and scope.
Lists: Ordered Collections
Store multiple items in a single variable. Learn to create, access, and manipulate lists.