A for loop repeats an indented block once for each value in a string, list, or other sequence. Python assigns each value to a loop variable automatically, so one loop can process thousands or millions of values without repeating the same code by hand. section 5.1.1
Read a for loop by checking these parts:
- The sequence after in supplies values, such as characters in a string or animals in a list. section 5.1.1
- The loop variable receives one value per iteration; char might receive each letter, while animal receives each list item. section 5.1.1
- Indentation marks the loop body, and every indented statement runs for each value. section 5.1.1 section 5.1.2
- Use range when the loop should visit a sequence of numbers or list indexes; range(3, 9) produces 3 through 8. section 5.1.1
- Choose a for loop when the values or number of iterations are known; choose a while loop when repetition ends only after a condition changes. section 5.1.1
Greeting every animal
lst = ['cat', 'dog', 'bird', 'fish'] for animal in lst: print('Got', animal) print('Hello,', animal) The loop assigns each animal in turn and runs both indented print statements before moving to the next item. A range-based version can use an index: for index in range(len(lst)): print(lst[index]). section 5.1.1
Processing nested values
A loop can contain an if statement, such as checking for 'bird' while visiting each animal. Loops can also nest: iterating over countries inside another country loop produces every country pair. Indentation determines whether loops run consecutively or one inside the other. section 5.2 section 5.1.2
Listing 5.2 Example using a for loop
>>> lst = ['cat', 'dog', 'bird', 'fish']
>>> for animal in lst: #1
... print('Got', animal) #2
... print('Hello,', animal) #2
...
Got cat
Hello, cat
Got dog
Hello, dog
Got bird
Hello, bird
Got fish
Hello, fish
Shows the loop variable changing across a list and demonstrates that multiple indented statements execute for every item. section 5.1.1


























