Lecture notes 4#
Sample exercises#
Assignment#
Assignment exercise with test. Testing is based on the assert
statement which verifies that an expression is true and report an error when it is false.
assert True, "Something is wrong"
assert False, "Something is wrong"
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[2], line 1
----> 1 assert False, "Something is wrong"
AssertionError: Something is wrong
Assignment =
vs comparison ==
bobs_age = 86
assert bobs_age == 86
f-strings#
substituting values into strings. The print function combines any number of arguments to a single string which is displayed on the screen
print("Bob is", bobs_age, "years old.")
Bob is 86 years old.
To substite part of a string with a value, curly braces are used as a placeholder. This does not quite do it
"Bob is {bobs_age} old."
'Bob is {bobs_age} old.'
But with a leading f
before the opening quotation mark we have the compact form, for substiting the value of bobs_age
into a string
f"Bob is {bobs_age} old."
'Bob is 86 old.'
Special use of fstring, useful in debugging where we often like to print
print(f'bobs_age={bobs_age}')
bobs_age=86
has the alternative form
print(f'{bobs_age=}')
bobs_age=86
Exercise: if statement#
MIN_DRIVING_AGE = 18
def allowed_driving(name, age):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant"""
if age >= MIN_DRIVING_AGE:
print(f'{name} is allowed to drive')
else:
print(f'{name} is not allowed to drive')
allowed_driving('John', 17)
John is not allowed to drive
allowed_driving('Jane', 19)
Jane is allowed to drive
print(age) # note that age is local to the function allowed_driving, it is not defined outside the function
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[64], line 1
----> 1 print(age)
NameError: name 'age' is not defined
Exercise: Looping (repetition)#
Consider
print(1)
print(2)
print(3)
1
2
3
this is repetition with a little variation. If we assign the varying value to a variable, the print statements are identiccal
e = 1
print(e)
e = 2
print(e)
e = 3
print(e)
1
2
3
This is effectively how for loops work
for e in [1, 2, 3]:
print(e)
1
2
3
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
def dedup_and_title_case_names(names):
"""Should return a list of title cased names,
each name appears only once"""
unique_names = []
for name in names:
name = name.title()
#print(name, unique_names)
if name in unique_names:
pass
else:
unique_names.append(name)
return unique_names
def sort_by_surname_desc(names):
"""Returns names list sorted desc by surname"""
names = dedup_and_title_case_names(names)
# ...
def shortest_first_name(names):
"""Returns the shortest first name (str).
You can assume there is only one shortest name.
"""
names = dedup_and_title_case_names(names)
# ...
dedup_and_title_case_names(NAMES)
['Arnold Schwarzenegger',
'Alec Baldwin',
'Bob Belderbos',
'Julian Sequeira',
'Sandra Bullock',
'Keanu Reeves',
'Julbob Pybites',
'Al Pacino',
'Brad Pitt',
'Matt Damon']
def test_dedup_and_title_case_names():
names = dedup_and_title_case_names(NAMES)
assert names.count('Bob Belderbos') == 1
assert names.count('julian sequeira') == 0
assert names.count('Brad Pitt') == 1
assert len(names) == 10
assert all(n.title() in names for n in NAMES)
test_dedup_and_title_case_names()
What methods are defined for strings?
dir("")
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
How about lists?
dir([])
['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getstate__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
help([].append)
Help on built-in function append:
append(object, /) method of builtins.list instance
Append object to the end of the list.
mylist = []
mylist.append('Joe')
mylist
['Joe']