CS 111 f21 — Lists and for loops

1 Repeated guesses

  • how would we give the user 5 guesses?
    • could copy paste the code, printing out a different number of guesses left each time

      import random
      # secret: generate a random number
      secret = random.randint(1, 100)
      print(secret)
      
      # guess: get user input
      guess = input("Enter your guess: ") # parameter is the prompt
                                          # returns user's input (as text)
      # convert guess to an integer
      guess = int(guess)
      
      def get_hint(guess, secret):
          # they guessed correctly
          if guess == secret:
              return ("WINNER!!!!!")
          # lava is within 5
          elif abs(guess - secret) < 5:
              return ("lava")
          # warm is within 10
          elif abs(guess - secret) < 10:
              return ("warm")
          else:
          # colde is everything else
              return ("colde")
      
      print(get_hint(guess, secret))
      if guess != secret:
          print("You have 4 guesses left")
          guess = input("Enter your guess: ") 
          guess = int(guess)
          print(get_hint(guess, secret))
      
      if guess != secret:
          print("You have 3 guesses left")
          guess = input("Enter your guess: ") 
          guess = int(guess)
          print(get_hint(guess, secret))
      
      if guess != secret:
          print("You have 2 guesses left")
          guess = input("Enter your guess: ") 
          guess = int(guess)
          print(get_hint(guess, secret))
      
      if guess != secret:
          print("You have 1 guesses left")
          guess = input("Enter your guess: ") 
          guess = int(guess)
          print(get_hint(guess, secret))
      
      if guess != secret:
          print("Better luck next time!")
      
    • potential problems with this approach?
  • fortunately, Python gives us a way to manipulate the instruction pointer to repeat a section of code

1.1 The for loop

for loop_variable in SEQUENCE:
    # repeated code goes here
    # more repeated code
# this code is not repeated
  • The loop starts be assigning loop_variable to the first thing in SEQUENCE
  • When the computer reaches the end of the loop (the end of the indented code), it checks if there is a next thing in the sequence
    • If there is, the computer goes back to the beginning of the loop, and assigns loop_variable to the next thing
    • If not, the computer exits the loop, continuing with the code below it
    • Each time through the steps inside a loop is called an iteration
for guesses_left in [5, 4, 3, 2, 1]:
    if guess != secret:
        print("You have", guesses_left, "guesses left")
        guess = input("Enter your guess: ")
        guess = int(guess)
        print(get_hint(guess, secret))
if guess != secret:
    print("Better luck next time!")

  • [5, 4, 3, 2, 1] creates a sequence of the five values inside the square brackets
    • In Python, a sequence inside square brackets is called a list

1.1.1 Practice

  • What will be printed?1 Note: unlike functions, loops are not their own little worlds.

    y = 2
    for y in [9, 3, 6, 1, 13]:
        print(y)
    print(y)
    
  • What will be printed?2

    x = 10
    result = 0
    for y in [9, 3, 6, 1, 13]:
        if x > y:
            result = result + 1
        else:
            result = result - 1
        x = y
    print(result)
    

2 Graphics Example

Computers aren't just for helping us with mechanical or informational tasks, they can be aesthetic or creative tools as well. The code below is linked from the calendar as art.py.

# for loop example using Portable Graphics Library
# requires pgl.py
# CS 111, Aaron Bauer

from pgl import GWindow, GOval # import what we need from Portable Graphics Library
import random
from random_graphics import random_color, start_random_move

# these are constants, values set at the start of the program that should never change
# have all caps names by convention
GWINDOW_WIDTH = 500
GWINDOW_HEIGHT = 800

# first thing is to create the graphics window (GWindow) that will 
# display our graphics, and set its width and height
gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT)
circle = GOval(250, 250, 100, 100)
gw.add(circle)
# you would think that position (250, 250) would be the center of the window
# so why does the circle appear off center?
# (250, 250) is the center, but the position we give the circle is the location of its UPPER-LEFT CORNER

count = int(input("How many circles would you like? "))

# repeat the following code count number of times
for i in range(0, count):
    # create a circle at a random position
    # the x and y position we give the circle is the location of its upper-left corner
    # same idea for y
    circle = GOval(random.randint(0, GWINDOW_WIDTH), random.randint(0, GWINDOW_HEIGHT), 10, 10)
    circle.setFilled(True) # make the circle filled in with color
    circle.setFillColor(random_color()) # set the color filling in the circle randomly
    gw.add(circle) # the circle won't appear unless we add it to the GWindow

start_random_move(gw, 10, 50)

2.1 Portable Graphics Library (PGL)

  • Developed by Eric Roberts, a computer scientist at Stanford
  • You will need pgl.py in order to use it
  • We create a window to display graphics using GWindow
    • We tell GWindow how big it should be by providing width and height as paramters
  • We create a circle using GOval
    • We need to tell it where to put the circle (an x and y position) and how big the circle should be (width and height)
    • In PGL, the origin (location 0,0) is in the upper left
  • In order for our circle to show up in our window, we need to add it to the window

    from pgl import GWindow, GOval
    gw = GWindow(500, 800)
    circle = GOval(250, 250, 100, 100)
    gw.add(circle)
    

2.2 range

  • We've seen how to create a sequence (a list) by putting values inside square brackets, separated by commas
  • But in these cases, we've specified exactly what those values were—what if we need a sequence that we don't know ahead of time?
    • For example, what if we want the user to choose how many circles appear on the screen?
  • We can use the built-in range function to generate a sequence of integers:

    • range(START, STOP) will return a sequence of integers from START up to, but not including STOP
    for x in range(5, 10):
        print(x)
    

    will print out

    5
    6
    7
    8
    9
    

2.2.1 range mystery

What will be printed?3

1: x = 0
2: for i in range(2, 6):
3:     x = x + i
4: print(x)
  • line trace: 1, 2, 3, 2, 3, 2, 3, 2, 3, 4

2.2.2 Unrolled

If we replaced the above for loop with equivalent code that doesn't use a loop, we would have

x = 0
i = 2
x = x + i
i = 3
x = x + i
i = 4
x = x + i
i = 5
x = x + i
print(x)

3 Pair programming

Read the guidelines closely!

Footnotes:

1
9
3
6
1
13
13
2
  • First loop iteration: x is 10, y is 9, we add 1 to result
  • Second loop iteration: x is 9, y is 3, we add 1 to result
  • Third loop iteration: x is 3, y is 6, we subtract 1 to result
  • Fourth loop iteration: x is 6, y is 1, we add 1 to result
  • Fifth loop iteration: x is 1, y is 13, we subtract 1 to result
  • That leaves result as 1, and that's what is printed
3

14, because x will be 2 + 3 + 4 + 5