ENGG1330
Computer Programming I
421 submissions · 403–404 answers to these questions
inventory = ['key']backup = inventoryinventory[0] = 'map'print(backup)x = ['key']y = ['key']print(x == y)== compares values
These two lists contain the same item
x = ['key']y = ['key']print(id(x))print(id(y))id(x) identifies the object
Equal values, different objects: their IDs differ
x = ['key']y = xprint(x is y)is checks for the same object
Both names refer to the same list
Diagram labels O1, O2, … stand for objects
They are not the numbers returned by id()
first = [10, 20]second = [10, 20]alias = firstprint(first == second)print(first is second)print(first is alias)first = ['key']alias = firstbefore = id(first)alias[0] = 'map'print(first, alias)print(id(first) == before)first = ['key']alias = firstfirst = ['map']print(first)print(alias)print(first is alias)word = 'door'other = wordword.upper()print(word, other)word = word.upper()print(word, other)ENGG1330
Computer Programming I
number = (0)packed = (0,)also_packed = 0,print(type(number))print(type(packed))print(packed, also_packed)values = (1, 2)previous = valuesvalues += (3,)print(previous, values)print(values is previous)values = [1, 2]previous = valuesvalues += [3]print(previous, values)print(values is previous)a = [1]b = ax = (1,)y = xa += [2]x += (2,)print(b)print(y)def show_product(x, y): print(x * y)def multiply(x, y): return x * yresult = show_product(3, 4)print(result)result = multiply(3, 4)print(result)print shows output
return sends a value to the caller
| After show_product(3, 4) | Value |
|---|---|
| Output on screen | 12 |
| result | None |
There is no return in this function
print(result) displays None
The screen now shows 12, then None
| After multiply(3, 4) | Value |
|---|---|
| Returned value | 12 |
| result | 12 |
The final print displays 12
point = (1, 2, 3)x, y, z = pointprint(x, y, z)Packing groups values in one tuple
| Tuple Item 0 | Tuple Item 1 | Tuple Item 2 |
|---|---|---|
| 1 | 2 | 3 |
Unpacking assigns items to names, in order
| x | y | z |
|---|---|---|
| 1 | 2 | 3 |
Use one target per item
() is an empty tuple
An iterable supplies items one at a time
Tuples, strings, and ranges are iterable
x, y, z = (1, 2, 3)a, b, c = range(3)first, second = 'Hi'print(x, y, z)print(a, b, c)print(first, second)def quotient_remainder(a, b): return a // b, a % bresult = quotient_remainder(17, 5)print(result)quotient, remainder = resultprint(quotient, remainder)x, y = (1, 2, 3)print(x, y)rows = ()for i in range(3): rows += ((i, i * 2, i * 3),)print(rows)for x, y, z in rows: print(x, y, z)values = (2, 5, 4)names = ('Ada', 'Ben')print(min(values))print(max(values))print(len(names))min finds the smallest value; max finds the largest
| Value | Name |
|---|---|
| 2 | Ada |
| 5 | Ben |
| 4 | Ada |
Collect every value, but each name only once
Three records give two distinct names
The three summary results
| Minimum | Maximum | Names |
|---|---|---|
| 2 | 5 | 2 |
Assume at least one record
def summarize(records): values, names = (), () for value, name in records: values += (value,) if name not in names: names += (name,) return min(values), max(values), len(names)records = ((2, 'Ada'), (5, 'Ben'), (4, 'Ada'))print(summarize(records))def show(x, y, z): print(x, y, z)point = (1, 2, 3)show(point)show(point) passes one tuple
The function needs three arguments
def show(x, y, z): print(x, y, z)point = (1, 2, 3)show(1, 2, 3)show(point[0], point[1], point[2])show(*point)*point unpacks its items into separate arguments
All three calls supply the same values
def difference(x1, y1, z1, x2, y2, z2): return x2 - x1, y2 - y1, z2 - z1start = (1, 2, 3)end = (4, 6, 8)print(difference(*start, *end))x, y = 3, 8temporary = xx = yy = temporaryprint(x, y)x, y = y, xprint(x, y)pair = ([1, 2], [3, 4])pair[0] = [9, 9]print(pair)pair = ([1, 2], [3, 4])pair[0][0] = 9print(pair)ENGG1330
Computer Programming I
values = [1, 2]values.append([3, 4])print(values)print(len(values))values = [1, 2]values.extend([3, 4])print(values)print(len(values))values = [1, 2]alias = valuesvalues = values + [3]print(values, alias)print(values is alias)values = [4, 7, 4, 9]del values[1]print(values)values.remove(4)print(values)values = [3, 1, 2]alias = valuesresult = values.sort()print(values, alias)print(result)values = [3, 1, 2]ordered = sorted(values)print(values)print(ordered)print(values is ordered)original = [1, 2]copied = original[:]copied[0] = 9print(original, copied)print(original is copied)original = [[1, 2], [3, 4]]copied = original[:]copied[0][1] = 9print(original)print(original is copied)print(original[0] is copied[0])a = [1, 2]b = [3, 4]c = [1, a, b]d = [a, c]a[1] = 42print(c)print(d[0] is c[1])a = [1, 42]c = [1, a, [3, 4]]d = [a, c]a = [5, 6]d[0] = 1c[1][1] = 3print(a)print(d)a = [[1], [2]]b = a[:]b[0].append(9)print(a)b[0] = [7]print(a, b)Predict both output lines
Which statement changes the shared inner list?
def remove_blocked(values, blocked): for value in values: if value in blocked: values.remove(value)values = [1, 2, 3, 4]blocked = [1, 2]remove_blocked(values, blocked)print(values)def remove_blocked(values, blocked): for value in values[:]: if value in blocked: values.remove(value)values = [1, 2, 3, 4]blocked = [1, 2]remove_blocked(values, blocked)print(values)ENGG1330
Computer Programming I
squares = []for number in range(5): squares.append(number * number)print(squares)squares = [number * number for number in range(5)]print(squares)numbers = [number for number in range(5)]print(numbers)evens = [n for n in range(8) if n % 2 == 0]inverses = [1 / n for n in range(-2, 3) if n != 0]print(evens)print(inverses)values = [1, 2, 3, 4]blocked = [1, 2]kept = [value for value in values if value not in blocked]print(kept)print(values)result = [n * n for n in range(6) if n % 2 == 1]
Write the equivalent loop, then predict the result
import randomrandom.seed(7)print(random.randint(1, 6))print(random.choice(('pass', 'retry')))A module groups reusable code
import random makes its functions available
seed(7) sets a repeatable starting state
The dot selects a function from the module
randint(1, 6) chooses an integer from 1 to 6
Both limits are included
choice selects one item from a sequence
Run twice and compare the outputs
import randomrandom.seed(7)rolls = [random.randint(1, 6) for roll in range(5)]print(rolls)ENGG1330
Computer Programming I
with open('demo.txt', 'w') as file: print('File is open')print('The block has ended')open opens a file
'w' creates or replaces it; as file names the file object
Indented statements run inside the with block
The file is open here
Leaving the block closes the file
'r' opens an existing file for reading
Later examples add encoding='utf-8'
This selects the text encoding
with open('demo.txt', 'w') as file: file.write('key\nmap\n')with open('demo.txt', 'r') as file: print(repr(file.read()))with open('demo.txt', 'r') as file: for line in file: print(repr(line))write(text) writes a string
\n separates the two lines
read() returns all remaining text
repr makes newline characters visible
A file is iterable
for line in file: reads one line at a time
Each line can include its newline
with open('demo_ids.txt', 'w', encoding='utf-8') as file: file.write('1001\n1002\n1003\n')with open('demo_ids.txt', 'r', encoding='utf-8') as file: text = file.read()print(repr(text))with open('demo_ids.txt', 'w', encoding='utf-8') as file: file.write('1001\n1002\n1003\n')ids = ()with open('demo_ids.txt', 'r', encoding='utf-8') as file: for line in file: ids += (int(line.strip()),)print(ids)print(len(ids), ids[1])import randomrandom.seed(7)ids = (1001, 1002, 1003)with open('demo_results.txt', 'w', encoding='utf-8') as file: for identifier in ids: outcome = random.choice(('pass', 'retry')) file.write(f'{identifier},{outcome}\n')with open('demo_results.txt', 'r', encoding='utf-8') as file: print(file.read(), end='')L5 Survey
Complete the survey during the lecture
L5 Coding Challenges
Work independently on the four challenges