CS 111 f21 — Practice with Loops and Lists

1 Review

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

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

What will be printed?2

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

What gets printed?3

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         # initialize the accumulator variable
    for num in nums:  
        total += num  # inside a loop, update the accumulator
    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 practice

  • 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.4
  • What gets printed?5

    nums = [1, 1]
    n = 5
    for i in range(2, n):
        nums.append(nums[-1] + nums[-2])
    print(nums)
    
  • Write loops to print the following:6

    X
    XX
    XXX
    XXXX
    XXXXX
    

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

Footnotes:

1

There will be an IndexError because the list has no element at index 5 (only 0 through 4)

2

16 25 36

3

[0, 0, 0, 0, 0]

4
def is_sorted(nums):
  for i in range(1, len(nums)):
    if nums[i] < nums[i - 1]:
      return False
  return True
5

[1, 1, 2, 3, 5]

6
rows = 5
for i in range(rows):
  for x in range(i + 1):
    print("X", end="")
  print()