COS 100: Introduction to Programming
Interim 2022
Lab 23: Bonus lab
Due to time constraint in this course, we've skipped over a lot of things.
This optional bonus lab contains a few ideas that are very useful.
Lab 23A: Control flow in loops
- In the body of a
for
or a while
loop, you can use continue
to skip the rest of the loop and start the next iteration or use break
to get out of the loop.
-
Run this code to understand the effect of
break
and continue
:
i = 0
while True:
if i == 10:
break
i = i + 1
print(i)
if i % 2 != 0:
continue
print("even:", i)
- Suppose
gradebook.txt
has the following format:
# max score
Max Perfect,6,10,20,20
# what follows are students
Rory Gilmore,5,9,13,7
Paris Geller,6,10,20,19
--
Paris, as always, did well.
Rory drifted off at the end.
where a line starting with #
is a comment to be ignored and a line that is just --
marks the end of student records (what's below should be ignored).
-
Modify your
load_file
from the gradebook homework project to ignore comments (lines starting with #
) and stop processing when (if) a line --
is reached.
- See Zelle 8.5 for more details.
Lab 23B: Exceptions
Lab 23C: String formatting
- Strings can include the value of other Python expressions.
-
Run the code below and deduce its usage:
name = input('Name, please: ')
number = int(input('Number, please: '))
print(f'Hi {name}. Do you also like {number + 1}?')
- What's the curly braces
{
and }
for?
What happens if you omit the f
in front of the string?
-
You can make pretty columns with some special features of formatted strings.
people = ['Alice', 'Bob', 'Chrysanthemum', 'Donald']
hourlyWages = [15.456, .8, 254.25, 20]
for k in range(len(people)):
print(f'{people[k]:15}{hourlyWages[k]:f}')
- Look at the official documentation
to see if you can figure out a way to force the hourly wages to be right-justified with exactly two digits beyond the decimal point.
- See Zelle 5.8.2 for related details.
Lab 23D: Dictionaries
- A dictionary can store key-value pairs.
wages = {'Alice': 15.456, 'Bob': .8, 'Donald': 20}
wages['Chrysanthemum'] = 254.25
print(wages)
print(wages['Alice'])
for name in wages:
print(name, wages[name])
del wages['Bob']
print('Alice' in wages)
print('Bob' in wages)
print(20 in wages)
for (name, wage) in wages.items():
print(name, wage)
- See Zelle 11.7 for more details.