CS 111 f21 — Lists and for loops part 2

Table of Contents

1 range Review

What will be printed?1

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

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)

What will be printed?2

x = 10
for change in range(5, 8):
    if change > x / 2:
        x = x + change
    else:
        x = x - change
print(x)

1.1 Default parameters

  • It turns out we can call range with 1, 2, or 3 parameters
  • range(START, STOP, STEP)
  • When STEP is left out, it's as if we called range with a step of 1
    • 1 is the default value
  • To get a sequence counting by 2s:
    for x in range(2, 20, 2):
      print(x)
    

    or count backwards

    for x in range(10, 0, -1):
      print("T-minus", x)
    print("BLASTOFF!!!")
    
  • When we call range with only 1 parameter, Python interprets this as a START of 0, and a STEP of 1, with the provided parameter as STOP
    for x in range(10):
      print(x)
    

2 The list

  • A kind of value that contains other data
    • think of it as a slot in memory with its own numbered slots inside
    • the first slot is number 0!

2.1 Temperatures, Once More With Feeling

  • Let's say our weather app has been upgraded, and now instead of a single current temperature, we have inputs from many different temperature sensors.
    cur_temps = get_cur_temps()
    print(cur_temps) # prints [76, 81, 78, 77]
    
    • We can access individual elements of a list with indexing (i.e., asking Python to retrieve the element at a particular numbered slot, or index)
    • print(cur_temps[0]) prints 76
    • print(cur_temps[3]) prints 77
    • print(cur_temps[4]) causes an IndexError
    • print(cur_temps[-2]) prints 78
  • Lists can be modified by using this same index syntax of the left side of an assignment
cur_temps[2] = F_to_C(cur_temps[2])
print(cur_temps)
  • Lists are a kind of sequence, which means for loops can iterate over them just like range objects
for temp in cur_temps:
    print(temp)
  • If we want to modify a list as part of a loop, this won't work:
    for temp in cur_temps:
        temp = F_to_C(temp)
    print(cur_temps) # still [76, 81, 78, 77]
    

    because inside the loop we are changing the variable temp, and not elements of the list

  • Indexing is our only way of modifying existing list elements
    for index in range(len(cur_temps)):
      cur_temps[index] = F_to_C(cur_temps[index])
    print(cur_temps) # prints [24.444444444444443, 27.22222222222222, 25.555555555555557, 25.0]
    
    • The len function takes a sequence and returns the number of elements in the sequence
    • range takes a stopping point
    • so for any sequence my_squence
      for index in range(len(my_sequence)):
      

      is a loop over the indexes of my_sequence

    • for element in my_sequence:
      

      is a loop over the elements of my_sequence

3 Poll

What will be printed?3

nums = [4, 5, 6]
for i in range(len(nums)):
    nums[i] = nums[i]**2
print(nums)

4 Loops within loops

  • Any code that can appear outside a for loop can appear inside a for loop, including another for loop
    line_lengths = [1, 0, 7, 1, 13, 1, 8]
    for length in line_lengths:
        for _ in range(length):
            print("*", end=" ") # put a space at the end of the line instead of moving to the next line
        print() # just prints a blank line
    
  • Can use PGL to make a graphical version:
from pgl import GWindow, GOval

GWINDOW_WIDTH = 500
GWINDOW_HEIGHT = 800
COLUMN_SIZE = 50

histogram_data = [1, 0, 7, 1, 13, 1, 8]
gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT)

x = 0
for column in histogram_data:
    y = GWINDOW_HEIGHT - COLUMN_SIZE
    for _ in range(column):
        circle = GOval(x, y, COLUMN_SIZE, COLUMN_SIZE)
        circle.setFilled(True)
        circle.setFillColor("Red")
        gw.add(circle)
        y = y - COLUMN_SIZE
    x = x + COLUMN_SIZE

5 Practice

  • You are given GWINDOW_WIDTH, GWINDOW_HEIGHT, BALL_SIZE, use these to place a solid blue circle at the top right corner of the window.4
  • Write a function to sum the elements of a list and return the result5
  • Write a pair of nested loops to print out a grid of Xs with 5 rows and 10 columns6

Footnotes:

1

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

2

The program will print 18

x change new x
10 5 5
5 6 11
11 7 18
3

16 25 36

4
circle = GOval(GWINDOW_WIDTH - BALL_SIZE, 0, BALL_SIZE, BALL_SIZE)
circle.setFilled(True)
circle.setFillColor("Blue")
gw.add(circle)
5
def sum(numbers):
    total = 0
    for number in numbers:
        total += number
    return total
6
for i in range(5):
    for j in range(10):
        print("X", end=" ")
    print()