CS 111 w20 lecture 8 outline

1 Poll

Why will this code cause an error and what kind of error will it be?

digits = ["3", "4", "5", "6", "7"]
print(digits[5])

What gets printed?

nums = [0, 1, 2, 3, 4]
for i in range(1, len(nums)):
    nums[i] = nums[i-1]
print(nums)

2 Exercise

Write a function sum that takes a list of numbers and returns the sum of those numbers.

def sum(nums):
    total = 0
    for num in nums:
        total += num
    return total

3 Nested loops

We want to write code that print this:

grid.png

where we have N_ROWS rows, each with N_COLS characters (with spaces in between), and the rows use the symbols #, *, @, and & in a repeating pattern.

3.1 The first row

N_ROWS = 6
N_COLS = 8
for i in range(N_COLS):
    # the end argument tells print to end the line with a space instead of a new line
    print("#", end=" ") 

3.2 Making a grid

N_ROWS = 6
N_COLS = 8
for j in range(N_ROWS):
    for i in range(N_COLS):
        print("#", end=" ") 
    print() # print a new line to go to the next row

3.3 Using the loop variable as an index

N_ROWS = 6
N_COLS = 8
SYMBOLS = ["#", "*", "@", "&"]
for j in range(N_ROWS):
    symbol = SYMBOLS[j % len(SYMBOLS)]
    for i in range(N_COLS):
        print(symbol, end=" ") 
    print() # print a new line to go to the next row

4 More list practice

  • Write a function max that takes a list of numbers and returns the greatest one. Assume the list is not empty.
  • Write a function is_sorted that takes a list of numbers and returns True if it is in ascending sorted order (smallest to largest), and returns False otherwise.
  • What gets printed?
nums = [1, 1]
n = 5
for i in range(2, n):
    nums.append(nums[-1] + nums[-2])
print(nums)

5 List methods

https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

  • list_var.remove(x) to remove the first element in the list equal to x (causes an error if there's no matching element)
  • list_var.index(x) returns the index of the first element in the list equal to x (causes an error if there's no matching element)
  • list_var.count(x) returns the number of times x appears in the list
  • list_var.sort() puts the list in ascending order, returns nothing (i.e., this rearranged the list itself, it doesn't return a new sorted list—use sorted(list_var) for that)
  • x in list_var evaluates to True is x is contained in the list, False otherwise