← Back to Blog

The loop that does the work for you

The problem...

You need to do something with every character in a word. So you write it for the first character. Then the second. Then the third.

There's a better way.

The idea!

A for loop repeats a block of code for every item in a sequence. You write the block once. Python runs it as many times as needed.

The syntax

for item in sequence:
    # runs once for every item

item is a variable that holds the current value on each iteration. sequence is anything Python can move through — one step at a time.

Your first for loop

word = "Bull"

for letter in word:
    print(letter)
# B
# u
# l
# l

Python goes through the string one character at a time. Each time, letter holds the current character and the block runs.

The loop variable is yours

You choose the name. Python just fills it in.

name = "RedHorn"

for character in name:
    print(character)

character, letter, c — all valid. Pick something that makes the code readable.

Doing something with each item

word = "Bull"

for letter in word:
    print(f"Current letter: {letter}")
# Current letter: B
# Current letter: u
# Current letter: l
# Current letter: l

The loop variable is just a variable. Use it however you need inside the block.

Counting with +=

You can use a variable outside the loop and update it on every iteration.

word = "Bull"
count = 0

for letter in word:
    count += 1

print(f"Letters counted: {count}")    # 4

The loop runs four times. Each time, count goes up by one. After the loop — the total is ready.

Checking your work with len()

len() returns the number of characters in a string. You've seen it before — now you know exactly what it's counting.

word = "Bull"
count = 0

for letter in word:
    count += 1

print(f"Counted manually: {count}")       # 4
print(f"Confirmed by len(): {len(word)}") # 4

Same result. Your loop did what len() does — one step at a time.

Heads up!

  • The for line ends with : — same rule as if
  • The block inside must be indented — 4 spaces
  • The loop variable name is up to you — pick something readable
  • Variables defined outside the loop are accessible inside it
  • If the sequence is empty — the block never runs, no error

The mindset shift

Stop thinking: "I'll write it once for each item."

Start thinking: "I'll write it once. The loop handles the rest."

What you should understand now

  • for iterates over a sequence — one item at a time
  • The loop variable holds the current item on each iteration
  • Variables outside the loop can be updated inside it with +=
  • len() returns the number of characters in a string
  • The block runs once per item — automatically
[ login to bookmark ] // copied! 33 views · 2 min
// resources
Code Example for_loops.py
← prev Ternary Mini Project — Your ticket, your price next → From here to there — range()
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.