Week 2
Week 2
Week 2
1
Plan for today
1. Dictionaries
2. Conditions
3. Control structures
1. Conditional statements and expressions
2. for-loops
3. Looping over collections of data
4. while-loops
4. Rest
1. Conversion of data types
2. Truthy and Falsy
3. Float is not precise 2
Dictionaries
• We saw last week: dictionaries are sets of key: value pairs:
{key1: value1, key2: value2, etc}
• Why dictionaries
1. Using dictionaries makes your program a bit more readable
• Compare:
• countries = ['Andorra', 'Belgium', …]
capitals = ['Andorra la Vella', 'Brussels', …]
print(capitals[countries.index('Netherlands')])
• capitals = ['Andorra', 'Andorra la Vella', 'Belgium', 'Brussels', …]
print(capitals[capitals.index('Netherlands') + 1])
• capitals = {'Andorra': 'Andorra la Vella', 'Belgium': 'Brussels', …}
print(capitals[ 'Belgium'])
2. Using dictionaries makes your program a bit more maintainable
• Compare adding a new country in those set-ups
• However last week we said using functions or objects to organize the code would hide the mess:
• If you can use for example:
insert(country = 'Friesland', capital = 'Leeuwarden')
you don't care how the function stores the data (lists, dictionaries, dataframes, databases etc.)
you can even change the way you store your data, while everyone still uses: the insert functions in the
old way 3
Dictionaries
• We saw last week: dictionaries are sets of key: value pairs:
{key1: value1, key2: value2, etc}
3. Dictionaries are rather fast
• Python uses dictionaries to show us and even let us change the values of variables, for
example it uses the locals() dictionary to keep track of the values of variables
• a = 2
print (locals()['a']) # Onscreen: 2
• locals()['b'] = 5
print(b) # Onscreen: 5
• There is with computer languages, always a trade-off between speed and flexibility:
To make dictionaries fast:
• Keys must be unique and immutable
• Dictionaries have no order like lists have, so you cannot sort them
print ([1,2] == [2,1]) # Onscreen: False
print ({1:1, 2:2} == {2:2, 1:1}) # Onscreen: True
4
Dictionaries
• We saw last week: dictionaries are sets of key: value pairs:
{key1: value1, key2: value2, etc}
4. If speed is no issue for you and you can hide everything in functions and objects, then why
dictionaries?
• "It is the Pythonic way to do."
5
Dictionaries
• How to create an empty dictionary:
• capitals = {}
• capitals = dict()
• How to create a filled dictionary:
• capitals = {'Andorra': 'Andorra la Vella', 'Belgium': 'Brussels}
• l1 = ['Andorra', 'Belgium']
l2 = ['Andorra la Vella', 'Brussels']
capitals = dict(zip(countries, capitals))
• Selection by key:
print(capitals['Belgium'))
• Delete key:value pair by:
del(capitals["Belgium"]) 6
Dictionaries
9
Compare lists with dictionaries
• Inserting new value:
• countries += ['Netherlands', …]
• countries.append('Netherlands')
11
Creating simple conditions
• Conditions are expressions that lead to True or False
• Comparison operators: <, <=, >, >=, ==, !=
Compare two values, the result is either True or False
print(1<1) # Onscreen: False
print(1<=1) # Onscreen: True
print(1>1) # Onscreen: False
print(1>=1) # Onscreen: True
print(1==1) # Onscreen: True
print(1!=1) # Onscreen: False
• Inclusion check: in
To check whether a value is in a collection. In case of a dictionary whether
the value is one of the keys.
print(1 in [1,2,3]) # Onscreen: True
print(1 in (1,2,3)) # Onscreen: True
print('1' in '123') # Onscreen: True
print(1 in {1: 4,2: 3}) # Onscreen: True
print(4 in {1: 4,2: 3}) # Onscreen: False
print(1 in {1,2,3}) # Onscreen: True
12
Using: boolean operators to make more
complex conditions
• Boolean operators to connect comparisons: and, or
print(True and True, True or True) # Onscreen: True True
print(True and False, True or False) # Onscreen: False True
print(False and True, False or True) # Onscreen: False True
print(False and False, False or False) # Onscreen:
False, False
• With this small set of building blocks, you can construct very complex
conditions 13
A tricky example
• But it can be Tricky, say you want only to get True only if both
variables a and b are either 1 or 2:
• a=1
b=3
print(a==1 or a==2 and b==1 or b==2)
• Makes sense? To a human, but not to Python. Let's see what Python
will make of this (In nerdy language how does Python evaluate this
code):
• Step 1: Python replaces the comparisons by their Boolean values
• Result: print(True or False and False or False)
• Step 2: Python executes the and
• Result: print(True or False or False)
• Step 3: Python executes the or's from left to right
• Result: print(True) #Onscreen: True 14
Comparison and boolean operators
• This is clearly not what you want. So, in case of doubt use round brackets:
a=1
b=3
print((a==1 or a==2) and (b==1 or b==2)) #Onscreen:
False
• An even nicer solution (applicable in this case) is using the inclusion
operator:
a=1
b=3
print(a in [1,2] and b in [1,2]) #Onscreen: False
• The whole problem about what Python does first, and what it does second
etc, is called the problem of precedence. As in the above example, you
can often avoid the problem, but in casf you are interested here a detailed
overview of precedense in the offical Python manuel:
https://docs.python.org/3/reference/expressions.html#operator-precedence15
Conditions, why?
• Now we know how to create conditions (expressions that evaluate
into True or False), what are we going to do with them?
• Use in conditional statements
• Use in loops
16
Conditional statements
• Now we know how to create conditions (expressions that evaluate into
True or False), what are we going to do with them?
• if condition_1:
expression_1
elif condition_2:
expression_2
expression_3
else:
expression_4
• You always have exactly one if (always at the start), at most one else
(always at the end), and as many elif's in between as you want.
• You see here indention used. After a colon you always have to indent your
code. All code that belongs together should get the same indention.
17
Conditional expressions, a useful short-cut
• Conditional statement
if a > 0:
b = a
else:
b = 0
• Conditional expression
b = a if a > 0 else 0
• Using conditional expressions, makes your code more concise, but this comes with a
trade-off:
• It enhances your overview
• It makes the code a bit more complex
• The more experience you get programming, probably the more you will choose this kind
of short-cuts. In future lectures we will discus comprehensions, and those really makes
18
your code more concise.
Loops
• Loops repeat code, this is useful, as it reuses code and
therefore makes your code easier to read and maintain
19
For-loop
• For variable in sequence:
expression
• Python executes the expression a given number of
times or for a given number of elements
• You can manipulate this default behavior with
break and continue
• Before each execution of the expression, the variable
is filled with one element after the other from the
sequence, until the sequence is exhausted
20
For-loops: examples
• You want to get the total of a series of numbers
• total = 0
for number in [1, 2, 3, 3, 5, 7]:
total += number
print (total) # Onscreen: 21
• You want to get the total of a series of numbers, but stop when encountering 99
• total = 0
for number in [1, 2, 3, 99, 5, 7]:
if number == 99:
break
total += number
print (total) # Onscreen: 6
21
For-loops: examples
• You want to get the total of a series of numbers, but skip the string values
• total = 0
for number in [1, 2, '3', 3, 5, 7]:
if type(number) == str:
continue
total += number
print (total) #Onscreen: 18
• You are not forced to use the variable in the expression:
• # total = 0
for number in range(5):
print ('Hello') #Onscreen: Hello Hello Hello Hello Hello
• If you want to make this more readable (or so I think):
• # total = 0
for _ in range(5):
print ('Hello') #Onscreen: Hello Hello Hello Hello Hello
22
Looping over dictionaries
• You can loop over sequences, but dictionaries are no sequences
• You can create sequences from dictionaries
• Say you have a dictionary:
capitals = {'Andorra': 'Andorra la Vella',
'Belgium': 'Brussels'}
• capitals.keys() gives you a sequence of dictionary keys
• capitals.values() gives you a sequence of dictionary values
• capitals.items() gives you a sequence of tuples with for each
pair the key and the value
23
Looping over dictionaries: examples
capitals = {'Andorra': 'Andorra la Vella', 'Belgium': 'Brussels'}
for key in capitals.keys():
print(key) # Onscreen: Andorra Belgium
for key in capitals.values():
print(key) # Onscreen: Andorra la Vella Brussels
for key, value in capitals.items():
print(key, value) # Onscreen: Andorra Andorra la Vella
# Belgium Brussels
• Tricky
for key in capitals:
Is the same as
for key in capitals.keys():
24
Enumerate another useful sequences for looping
• Say we have:
countries = ['Andorra', 'Belgium']
• Say you want to loop over this list, but for each of the values you also need its
index
for index, country in enumerate(countries):
print('country ' + country + ' has index: ' + str(index))
# Onscreen: country Andorra has index: 0 …
25
Zip another useful sequences for looping
• Say we have:
countries = ['Andorra', 'Belgium', …]
capitals = ['Andorra la Vella', 'Brussels', …]
• Say you want to loop over these lists in tandem, so for every country you also
need the capital
for country, capital in zip(countries, capitals):
print('country ' + country + ' has capital: ' + capital)
# Onscreen: country Andorra has capital: Andorra la Vella …
• You can zip more than 2 sequences.
• It is best you zip sequences of equal length, so you don't have to learn how
Python deals with sequences of unequal length
• You can zip sequences of different types
26
While-loop
• while condition:
expression
• Executes the lines in the expression, as long as the condition is
True
• Python first checks the condition before the expression is evaluated
• You can also use break and continue
• Watch out for infinite loops!
• Especially on a (free) PythonAnywhere account
• Use Ctrl + C, if you accidentally get into one.
• If it all goes wrong, you must wait 24 hours.
27
While-loop: example
• In general, avoid the while-loop as much as you can!
• With for-loops you know beforehand how many data you must process at
most:
total = 0
for number in [1, 2, 3, 99, 5, 7]:
if number == 99:
break
total += number
print (total) #Onscreen: 6
• You know this most of the time, with pandas you can for example read a
whole spreadsheet and then ask how many data you have
28
While-loop: example
• But there are situations, when you don't know, how many data you must process at
most.
• Your program asks the user to enter numbers to get a total in return. When the user
wants to stop the user enters 99. That is a good case for a while-loop.
total = 0
number = int(input("give a number, or 99 to stop "))
while number != 99:
total += number
number = int(input("give number, or 99 to stop "))
print (total)
• or
total = 0
number = int(input("give a number, or 99 to stop "))
while True:
if number == 99:
break
total += number
number = int(input("give number, or 99 to stop "))
print (total)
• Why are both solutions still a bit ugly?
• Repetition of code! Maintenance problem. That is solved however: 29
The walrus operator(Python 3.8+)
total = 0
while number := int(input("give a number, or 99 to stop ")):
if number == 99:
break
total += number
print (total)
• The walrus operator let's you eat your cake and have it:
• You define the variable and use it on the same spot
• It can be used in other situations, but this is a good place
30
Compare for-loop and while-loop
• Anything you can do with a for loop you can also do with a while-
loop, but as we saw, you can even do more
• So, if you really don't know how to solve a looping problem with a for-
loop, you can always use a while-loop.
31
Conversion of datatypes
• Compared with other programming languages, Python is not very generous w.r.t.
automatically converting datatypes
• Print('1' + 1) # Onscreen: error, the designers of Python could have
chosen automatic conversion of the string '1' into integer 1
• Print('1.0' +1) # Onscreen: error, the designers of Python could have chosen
automatic conversion of the string '1.0' into float 1.0
• Print(1232.count(2)) # Onscreen: error, the designers of Python could have
chosen automatic conversion of the integer 123 into string '123' and answer the question
• If you need these conversions, you have to make those conversions yourself
• Advantage: more control, less surprises. In JavaScript "1" + 2 + 3, gives you "123" and
not 6, you could be surprised as there is no error.
• Disadvantage: more work. Compare "page" + number, in JavaScript with: "page" +
str(number) in Python.
32
Truthy and Falsy: automatic conversion in
conditions
• We said Python is not very generous w.r.t. automatically converting datatypes
• Datatypes of variables used as a condition are the exceptions to the rule.
• When used as a condition the following is seen as True or False:
False True
[] [1]
() (1)
{} {1:3}
{} {1}
““ ““
0 2
0.0 2.0 33
Truthy and Falsy: an example
• l1 = [1, 2, 3, 4, 5, 6]
total = 0
while l1:
total += l1.pop()
print(total) # Onscreen: 21
• looks very similar to using a for loop, where you run over a
collection until it is exhausted:
• l1 = [1, 2, 3, 4, 5, 6]
total = 0
for number in l1:
total += number
print(total) # Onscreen: 21
34
Some examples of explicit conversions
• print(str(1) == '1') # Onscreen: True
• print(int("1") == 1) # Onscreen: True
• print(int("1a") == 1) # Onscreen: error
• print(float("1") == 1.0) # Onscreen: True
• print(float("1.0") == 1.0) # Onscreen: True
• print(tuple([1,2,3]) == (1,2,3)) # Onscreen: True
• print(tuple({1:3, 2:4}) == (1,2)) # Onscreen: True
print(list(range(1,5,2)) == [1, 3]) # Onscreen: True
• print(dict([1, 2])) # Onscreen: error
• print(dict([(1,3), (2,4)]) == {1: 3, 2:4})
• Some conversion functions: dict(), tuple(), list(), set(), int(), bool(),
float()
35
Integers are precise, but floats aren't
• Calculating with integers is flawless
print (2**1000) # Onscreen:
10715086071862673209484250490600018105614048117055336074437503883703510511249
36122493198378815695858127594672917553146825187145285692314043598457757469857
48039345677748242309854210746050623711418779541821530464749835819412673987675
59165543946077062914571196477686542167660429831652624386837205668069376
• Calculating with floats, not so much
Num1 = 10000.29
num2 = 10000.2
print (num1 – num2) # Onscreen: 0.09000000000014552
• Simpel solution:
Num1 = 1000029
num2 = 1000020
print ((num1 – num2) / 100) # Onscreen: 0.09
• For the homework, we use rounding, that's enough. This is just that you
know: in case of floats, what you see is not always what is stored 36
Homework week 1
• Try to understand the suggested solutions in the corrections email,
that is good for your exam and in general, the building blocks from
DataCamp should be enough to understand them. And if it is not
clear, play around with the code in Pythonanywhere.
37
Common errors
• Overwriting the testcase that test_answer.py wants to test
• SOLUTION BEING TESTED
=====================
x = 'Mary’
print('Good morning ' + x + '!’)
• TEST RESULT
===========
FAILED TEST!
• Preconditions
‾‾‾‾‾‾‾‾‾‾‾‾‾
x = 'Bernard’
• Expected printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Good morning Bernard!
• Actual printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Good morning Mary!
• What test_answer.py wants to test you find under preconditions
• But here in your code (under solution being tested) you see that the first thing you do is overwrite Bernard with Mary
• So, your program gives Good morning Mary as output but test_answer expects of course good morning Bernard.
• So, get rid of x = ‘Mary’ by making it into a comment with a hashtag (#), or delete the line.
• A solution is not to change the first line in your code with x = ‘Bernard’ because every question is tested for with 20 different cases.
So, the next case could be: x = ‘Daniel’
38
Common errors
• Forgetting to save
• SOLUTION BEING TESTED
=====================
x = 'Mary’
print('Good morning ' + x + '!’)
• TEST RESULT
===========
FAILED TEST!
• Preconditions
‾‾‾‾‾‾‾‾‾‾‾‾‾
x = 'Bernard’
• Expected printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Good morning Bernard!
• Actual printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Good morning Mary!
• Say, you were sure you took x = ‘ Mary’ out. The problem could be that you didn’t save your new version.
• Not saving is the most common and most annoying error.
39
Common errors
• Not looking at expected and actual printout can make you too pessimistic
• SOLUTION BEING TESTED
=====================
print([x[0], x[1], x[3]])
• TEST RESULT
===========
FAILED TEST!
• Preconditions
‾‾‾‾‾‾‾‾‾‾‾‾‾
x=['yv’,'ok','z','s’]
• Expected printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
['yv', 'z', 's']
• Actual printout
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
['yv', 'ok', 's’]
• Have a good look at the expected and actual printout and you will think, ha almost correct, I have to alter the code a bit,
must have used a wrong index. My impression is that students often when they see failed test!, think this is wrong and start
from scratch.
• This is maybe/probably a silly example, but in the later weeks it can really help to have a good look at the printouts40and try
to have a positive mindset.
Common errors
• Not understanding the template of the question
• ""“
Assume that you already have one variable called 'x', which is a list
that contains 4 elements.
• This is a silly example, but a lot of errors occur, because programmers forget what variable was meant by a
certain name. These errors can be very difficult to find, as Python doesn’t throw an error.
• Avoid using Python reserved words as names of your variables
countries = ['Netherlands', 'Belgium']
capitals = ['Amsterdam', 'Brussels']
sorted = sorted(countries)
sorted2 = sorted(capitals) # Onscreen: TypeError: 'list' object is
not callable
• If you use more meaningful names like sorted_countries or sorted_capitals you will be safe, or if you go in the
other direction l1, l2 etc also. But remember for Python also built-in functions etc. are just objects with a name
and you can accidentally attach that name to another object.
42
Programming strategy: working inside out
• Step by step
• n1 = 100
• n2 = x/100
• n3 = n2 + 1
• n4 = n1*n3**7
• n5 = round(n4, 3)
• Print(n5)
• Inside out
• x/100+1
• (x/100+1)
• (x/100+1)**7
• n1*(x/100+1)**7
• round(n1*(x/100+1)**7, 3)
• print(round(n1*(x/100+1)**7, 3))
• Trade-off
• No naming problems
• Better overview
• More complex
• It takes some experience to do the inside out method
43
Programming question: What does the
following program do?
X = X+Y
Y = X –Y
X = X – Y
44