(use the Space key to navigate through all slides)
Every day life, we often repeat tasks:
write Python programs that
repeat the same code execution
for variable in sequence:
# Code to repeat
passit allows us to execute a block of code multiple times, iterating over items in a sequence.
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)The loop picks the first name
("Alice") and prints it.
Then, it picks "Bob" ...
Then, ...
Each iteration automatically
moves to the next item!
word = "Python"
for letter in word:
print(letter)What Happens?
The loop prints each letter
one at a time!
(a string is also a sequence of characters)
range() Function# Starts at 1, stops before 6
for num in range(1, 6):
print(num)range(1, 6) generates[1, 2, 3, 4, 5]
We can use range(n) to repeat an action n times.
# `_` is a placeholder (we
# don't need the variable)
for _ in range(3):
print("Hello!")
A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations