Skip to main content

Section 4.6 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 you run it.)
The loop variable achar is automatically assigned each character in the string β€œGo Spot Go” one at a time. 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 4.6.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.

Checkpoint 4.6.2.

    How many times does the turtle in this code move to a random location?
    # Turtle name symbol drawing
    import turtle
    import random
    wn = turtle.Screen()
    annika = turtle.Turtle()
    s = input("Please enter your name")
    for ch in s:
       x = random.randrange(-200, 200)
       y = random.randrange(-150, 150)
       annika.goto(x, y)
    
  • 1
  • The turtle will move to as many locations as there are letters in the name.
  • 0
  • The turtle will move to at least one location.
  • 7
  • The turtle will move to as many locations as there are letters in the name.
  • It depends on the length of the name the user enters.
  • Yes, if the user enters "Sam", the turtle will move to 3 random locations.
You have attempted of activities on this page.