Previous Lecture Lec 14 Next Lecture

Lec 14, Wed 02/19

Objects (Mutability), Nested Loops, String Formatting

Wednesday, February 19th Lecture

# Generate num(candidate primes)
for num in range(start, end, step)
  #check the divisors
  for div in range(2,num/2 + 1):
    if num % div is divisible
      print (         )
      break
    #save the prime number

Example of printing columns and rows:

mtable = [[2, 3, 11], [5, 78, 99], [5777, 9978, 99]]:
for row in mtable:
  for elt in row:
    print (elt, " ", end = "")
  print()

Questions

What is the difference between break and continue?

=======

Lecture 14 (Thursday)

Review

Pseudocode for the prime number function (lab06)…

start = 2 # Example values
end = 8 # Example values
list_primes = []
for num in range(start, end):
    isPrime = True
    # use another loop to generate divisors
    for div in range(2, num//2 + 1):
        # check the divisors
        if num % div == 0:
            isPrime = False # will set isPrime to False once num is divisible by one of the divisors
            break # will exit inner for loop
        # if there are none, add the number to the list of primes
        if (isPrime==True): # Add a boolean flag to check that we only add the num to list if it is prime
            list_primes.append(num)

Mutability of objects

  1. What is printed out after running the following code segment?
pet = 'cat'
pet.replace("c","b")
print(pet)

LAB06 example

  1. What is printed out after running the following code segment?
tmp = [1,2,3]
myL = []
for i in range(4):
    myL.append(tmp)
myL[0][0] = 42

print(tmp)
myL = []
for i in range(4):
    tmp = [1,2,3]
    myL.append(tmp)
myL[0][0] = 42

print(tmp)
print(myL)

If we initialize tmp inside of the loop, a new tmp variable is created in each iteration of the for loop. That way, even though all of these lists look the same when they are initialized, they are not actually the same, so mutating one at the end by doing myL[0][0] = 42 will not change the values of the others.

We can visualize this by printing out the id of each list like so. In the first example, the ids are the same.

myL = []
tmp = [1,2,3]
for i in range(4):
    myL.append(tmp)
    print(id(tmp))
myL[0][0] = 42

print(tmp)
print(myL)

Compare it with:

myL = []
for i in range(4):
    tmp = [1,2,3]
    myL.append(tmp)
    print(id(tmp))
myL[0][0] = 42

print(tmp)
print(myL)

  1. What is printed out after running the following code segment?
my_pets = ["bat", "cat"]
ur_pets = my_pets
ur_pets.append("owl")
print(my_pets)

Answer: […]

  1. What is printed out after running the following code segment?
my_pets = ["bat", "cat"]
ur_pets = ["bat", "cat"]
ur_pets.append("owl")
print(my_pets)

Answer: […]

Formatting Output

for num in range(0, 10):
    print("{0:10.3f}".format(num))