You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Loops let you repeat a block of code multiple times. Python has two loop constructs: for loops (for iterating over sequences) and while loops (for repeating while a condition is true). Mastering loops is essential — they are one of the most powerful tools in programming.
for LoopA for loop iterates over a sequence (list, string, range, etc.):
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
# Loop through a string
for char in "Python":
print(char, end=" ")
# P y t h o n
range() Functionrange() generates a sequence of numbers — perfect for loops:
# range(stop) — 0 to stop-1
for i in range(5):
print(i, end=" ")
# 0 1 2 3 4
# range(start, stop)
for i in range(2, 6):
print(i, end=" ")
# 2 3 4 5
# range(start, stop, step)
for i in range(0, 20, 3):
print(i, end=" ")
# 0 3 6 9 12 15 18
# Counting backwards
for i in range(10, 0, -1):
print(i, end=" ")
# 10 9 8 7 6 5 4 3 2 1
while LoopA while loop repeats as long as its condition is True:
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
# Count is 0
# Count is 1
# Count is 2
# Count is 3
# Count is 4
Danger: If the condition never becomes False, you get an infinite loop:
# DON'T do this (infinite loop!)
# while True:
# print("This never stops!")
# But infinite loops with break are a common pattern:
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print(f"You typed: {answer}")
break — Exit a Loop Earlybreak immediately stops the loop:
# Find the first even number
numbers = [1, 3, 7, 8, 12, 15]
for num in numbers:
if num % 2 == 0:
print(f"First even number: {num}")
break
# First even number: 8
# Input validation loop
while True:
age = input("Enter your age (or 'quit'): ")
if age == "quit":
print("Goodbye!")
break
if age.isdigit():
print(f"You are {age} years old.")
break
print("Please enter a valid number.")
continue — Skip to the Next Iterationcontinue skips the rest of the current iteration and moves to the next:
# Print only odd numbers
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i, end=" ")
# 1 3 5 7 9
# Skip blank lines when processing text
lines = ["Hello", "", "World", "", "Python"]
for line in lines:
if not line:
continue
print(line)
# Hello
# World
# Python
else on LoopsPython has a unique feature — an else clause on loops. It runs when the loop completes without hitting a break:
# Search for a number
numbers = [1, 3, 5, 7, 9]
target = 4
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found in the list.")
# 4 not found in the list.
enumerate() gives you both the index and the value:
fruits = ["apple", "banana", "cherry"]
# Without enumerate
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.