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 without writing it out over and over. Python provides two main loop types: for and while.
A for loop iterates over a sequence — a list, string, range, or any iterable:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
range() generates a sequence of numbers:
for i in range(5):
print(i)
# 0 1 2 3 4
for i in range(1, 6):
print(i)
# 1 2 3 4 5
for i in range(0, 10, 2):
print(i)
# 0 2 4 6 8
range(start, stop, step) — stop is exclusive, step defaults to 1.
for char in "Python":
print(char)
# P y t h o n
A while loop repeats as long as its condition is True:
count = 0
while count < 5:
print(count)
count += 1
# 0 1 2 3 4
Always make sure something changes inside a while loop to eventually make the condition False — otherwise you get an infinite loop.
break exits the loop immediately:
for i in range(10):
if i == 5:
break
print(i)
# 0 1 2 3 4
continue skips the rest of the current iteration and moves to the next:
for i in range(10):
if i % 2 == 0:
continue
print(i)
# 1 3 5 7 9
Python loops can have an else block that runs when the loop completes normally (without hitting a break):
for i in range(5):
print(i)
else:
print("Loop finished!")
Loops can be nested inside each other:
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print()
# 1 2 3
# 2 4 6
# 3 6 9
When you need both the index and value while iterating, use enumerate():
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# 0: red
# 1: green
# 2: blue
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.