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
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.