For Loops
For Loops
Sometimes we want Python to do the same action again and again.
For example:
- Print a message many times
- Show each letter in a word
- Repeat a task without writing the same code again
A for loop helps us do that.
What Is a Loop?
A loop is code that repeats.
Instead of writing the same line many times, we write it once and let Python repeat it.
What Is a For Loop?
A for loop repeats code one step at a time.
It takes one item, uses it, then moves to the next item.
for letter in "cat":
print(letter)
How This Example Works
The word "cat" has three letters.
Python works like this:
- First letter is
c - Then letter is
a - Then letter is
t - After the last letter, the loop stops
Output
c
a
t
Another Example
for letter in "dog":
print(letter)
Using a Variable Name
The word after for is a variable name.
It stores the current item during each repeat.
for character in "hi":
print(character)
You can choose names like:
lettercharacteritem
Repeating a Message
A loop can also repeat another action.
for letter in "abc":
print("Welcome")
Because "abc" has three letters, Welcome prints three times.
Why Indentation Matters
The indented line is the code that repeats.
for letter in "go":
print(letter)
If the line is not indented, Python will show an error.
Code Along
name = "Sam"
for letter in name:
print(letter)
Mini Challenge
Build a name printer.
Steps:
- Store your name in a variable
- Use a
forloop - Print each letter on a new line
Real World Use Case
Programs use loops to read text, show products, send messages, and repeat tasks automatically.
Quiz
- What is a loop?
- What does a
forloop do? - What happens after the last item?
- Why is indentation important?
Assignment
Create a program that stores the word Python and prints each letter on a new line using a for loop.
Summary
You learned that a loop repeats code, and a for loop helps Python go through items one by one.