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

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

s = "python rocks"
for ch in s:
print "HELLO"

• (A) 10
• Iteration by item will process once for each item in the sequence.
• (B) 11
• The blank is part of the sequence.
• (C) 12
• Yes, there are 12 characters, including the blank.
• (D) Error, the for statement needs to use the range function.
• The for statement can iterate over a sequence item by item.

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

s = "python rocks"
for ch in s[3:8]:
print "HELLO"

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