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

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

    exceptions-2: How many times is the word HELLO printed by the following statements?

    s = "python rocks"
    for ch in s[3:8]:
       print("HELLO")
    
  • 4
  • Slice returns a sequence that can be iterated over.
  • 5
  • Yes, The blank is part of the sequence returned by slice
  • 6
  • Check the result of s[3:8]. It does not include the item at index 8.
  • Error, the for statement cannot use slice.
  • Slice returns a sequence.
Next Section - Traversal and the for Loop: By Index