Skip to main content

Foundations of Python Programming: Functions First

Section 7.4 Strings and for loops

Since a string is simply a sequence of characters, the for loop iterates over each character automatically. (As always, try to predict what the output will be from this code before your run it.)
The loop variable achar is automatically reassigned each character in the string “Go Spot Go”. We will refer to this type of sequence iteration as iteration by item. Note that the for loop processes the characters in a string or items in a sequence one at a time from left to right.
Check your understanding

Checkpoint 7.4.1.

    How many times is the word HELLO printed by the following statements?
    s = "python rocks"
    for ch in s:
       print("HELLO")
    
  • 10
  • Iteration by item will process once for each item in the sequence.
  • 11
  • The blank is part of the sequence.
  • 12
  • Yes, there are 12 characters, including the blank.
  • Error, the for statement needs to use the range function.
  • The for statement can iterate over a sequence item by item.
You have attempted of activities on this page.