Topic 2 Lists and Loops
Topic 2 Lists and Loops
Today
Functions: parameter and arguments
More code flow: loops (while, for)
lists, and list like objects
QOL Notes
When you write new code, and it doesn't work ...
start from the fewest lines of code possible (then expand after)
start with the smallest changes possible from code that works
typos, etc., are all a thing and hard to spot!
(Increase the size of your fonts)
work slowly
If you're using jupyter notebooks and things don't work
Restart the Python Code in the background by:
Menu > Kernel > Interrupt Kernel
And then run your code-cell again
If all fails, restart notebook completely (sad but true)
If jupyter acts like a complete mess on your system check with friend/me to see if
your code is wrong (most of the time it is) or whether something stranger is
happening (1/100 cases)
Try another coding environment (Pycharm, Visual Studio, etc.) if nothing works
IT Service Desk Plus (Wednesday/Thursdays, 14-16:00 at Info Desk 1F Library,
Info Desk )
example_arg_order("a", "b")
In [5]: y = "a"
x = "b"
example_arg_order(y, x)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[9], line 2
1 # This also does not:
----> 2 example_arg_order("b", x="a")
Default Values
An parameter in a function can have a predetermined value
Example: func(x, y, z=10)
Rule: parameters with default values (default argument) must follow non-default
argument (similar to argument/keyword argument rule)
Beautiful in two ways:
implement a standard-case automatically while building in flexibility
function call can skip arguments with default values
In [ ]: # This works:
def func_(x, y=5):
pass # pass is the empty function keyword.
Code Flow
Real Life Algorithm: Washing dishes
(imagine a world without waimai)
you cooked and ate with a friend, and now you have to wash the dishes
there are
4 chopsticks
6 bowls
2 plates
1 pan
2 glasses
1 pot
write an algorithm to clean those dishes (that you can give to your friend to do it)
A not very good algo
Take one chopstick, wash it, put it on the drying rack
Take one chopstick, wash it, put it on the drying rack
Take one chopstick, wash it, put it on the drying rack
Take one chopstick, wash it, put it on the drying rack
Take one bowl, wash it, put it on the drying rack
[...]
A slightly better algo
Check if there is a dirty kitchen item, take it, wash it, put it on the drying rack
Check if there is a dirty kitchen item, take it, wash it, put it on the drying rack
...
Check if there is a dirty kitchen item, take it, wash it, put it on the drying rack
A much better algo
[1.] Check if there is a dirty kitchen item
[1.1] if there is, take it, wash it, put it on the drying rack. Go back to [1.]
[1.2] if there is not. You are done : )
while Loop
while condition-is-true:
some code
a loop that keeps on repeating the code within as long as its condition is met
while loops are useful when the number of iterations needed is unknown at the
start (and depends on outcome of loop contents), e.g., dirty dish still exists
Two things are crucial when using a while loop:
in order to run (once), the logical expression should evaluate to true when loop
begins
you must update that condition (at least sometimes) inside the loop
otherwise, your loop runs forever
In [11]: i = 1 # Variables must be set before the while loop
while i<10: # Similar to the if-statement we know
print(f"i = {i}")
i = i + 1
# When reaching the end of the block of code,
# we go back to the beginning of the while-loop
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
Some syntax
in loops, we often want to add (subtract, etc.) to a given number, e.g. i = i + 1
simple syntax for this: i += 1, i -= 1, etc.
works for all typical mathematical operations: plus (+), minus (-), multiplication (*)
and division (/), exponentiation (**) and remainder, or modulo (%; e.g., 5 % 3 = 2)
note: you don't need to use these simplifications. they don't make you better
coders; they just help you write less :)
Hangman while loop
num_missed_guesses = 0
while num_missed_guesses < 7:
guess = input("Make a guess.")
main_code_goes_here()
Terminating while-loops
The keyword break can be used in a while loop to immediately terminate
execution.
This practise is of questionable coding quality, however
why? the while loop defines a clear condition for which it executes.
breaking in loop (say if i == 5: break ) introduces yet another condition
this makes it difficult to read code
lists
Lists are a built-in container data type which hold other data
e.g., floats, integers, complex numbers, strings or even other lists.
Basic lists are constructed using square braces, [] , with values are separated
using commas.
Example: a list of numbers (int/float) can be used to express a vector.
my_list = [5, 10, 35, 2]
Probably the most essential tool in Python programming
List properties
List items are ordered
implication: you can access them by their index, i.e., my_list[index]
for a one-dimensional list, the indices are 0, 1, ..., n-1
in coding, most numbered items start at 0!
and mutable (changable)
you can reasign values to a position to the list: my_list[2] = 2
(as well as many other operations, see later)
Example list
In [34]: my_list = [5, 10, 35, 7]
print(f"my_list = {my_list}")
In [13]: my_list[2] = 2
print(f"\nSet third list item to 2 yields: {my_list}")
In [37]: print(my_list[2:4])
[5, 7]
In [38]: print(my_list[1:])
[3, 5, 7, 9]
x[0] = [1, 2, 3, 4]
x[1][3] = 8
Play Guitar
for Loop
for item in sequence:
Code to run
a loop that iterates over a sequence (a list, or related container concepts (later),
general 'iterables', but even strings)
item is an item in the sequence (iterable), and can be accessed in the codeblock!
the loop will go over all items in the sequence
when the sequence is multidimensional, it will only go over the highest-level,
equivalent to x[0] , x[1] , etc.
unlike the while loop, it may make sense to terminate loop early with break
continue can be used to skip an iteration of a loop, immediately returning to the
top of the loop using the next item in iterable.
In [43]: my_preferred_breakfast = ['Coffee', 'Cashew Nuts', 'Cookies']
for x in my_preferred_breakfast:
print(x)
Coffee
Cashew Nuts
Cookies
Class Question: Write a for loop checks for cookies (and stops when found) in
my_preferred_breakfast = ['Coffee', 'Cashew Nuts', 'Cookies',
"Orange"]
Solution (click)
Interestingly: text is also iterable
In [45]: for character in "Gingerbread":
print(character)
G
i
n
g
e
r
b
r
e
a
d
turn_list_data_into_single_dataset()
Comment
Be careful when modifying the sequence itself when iterating.
(for now, best avoided) may cause unintended effects (unless you really know what
you are doing)
range()
A range is most commonly encountered in a for loop.
range(start, stop, step) creates a sequence of
with stop not included.
start, start + step, start + 2 ⋅ step, … , stop
<class 'range'>
[3, 4, 5, 6, 7, 8, 9, 10]
0
1
2
3
4
enumerate()
If you really wanted to know the index value, we can use the built-in enumerate
iterates over a list and returns both the index and item; access them as follows:
In [27]: list_num = [5,10,20,40]
for index, item in enumerate(list_num):
print(index, item)
0 5
1 10
2 20
3 40