liveBook · Manning

Loop variable

As explained in Get Programming: Learn to code with Python

A loop variable is a variable that receives successive items from a sequence during loop execution.

A loop variable receives a different item from a sequence on each repetition of a for loop. The loop body runs after each new value is assigned. section 16.4 section 16.3

Iterating over characters

for ch in "Python is fun so far!": print("the character is", ch) Here, ch is the loop variable. Python assigns it the first character, prints it, then assigns the next character and repeats until every character has been used. Spaces and punctuation count as characters too. section 17.2

A loop variable can take values from several kinds of sequences:

  • range(3) assigns 0, then 1, then 2, so the loop runs three times. section 16.3
  • A string assigns its characters directly, avoiding the need to use an index as a middleman. section 17.3
  • A while loop requires you to create, check, and increment the comparable variable yourself; a for loop handles those steps automatically. section 18.2
Listing 17.1. A for loop that iterates over each character in a string
for ch in "Python is fun so far!":               #1
    print("the character is", ch)                #2

Use the listing to trace how the loop variable changes from one character to the next. section 17.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains assignment and execution step by step, then contrasts automatic for-loop updates with manual while-loop control.
Examples
Uses range(3), character printing, string indices, counting exercises, and repeated-book messages as practice.
What you can do after
Apply it via Python for loops to process each number in a range or each character in a string.
How it connects
Links loop variables to for loops, sequences, range expressions, strings, indices, and while loops.

Also explained in

Compare how 2 books explain loop variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.