CodingNic

Loops and Iteration

For Loops

Loops and Iteration 20 min read

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.

python
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

text
c
a
t

Another Example

python
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.

python
for character in "hi":
    print(character)

You can choose names like:

  • letter
  • character
  • item

Repeating a Message

A loop can also repeat another action.

python
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.

python
for letter in "go":
    print(letter)

If the line is not indented, Python will show an error.

Code Along

python
name = "Sam"

for letter in name:
    print(letter)

Mini Challenge

Build a name printer.

Steps:

  • Store your name in a variable
  • Use a for loop
  • 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

  1. What is a loop?
  2. What does a for loop do?
  3. What happens after the last item?
  4. 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.