Continuation Course in Programming in Python
Lecture 2:
Python recap and tutorial II
Chalmers/GU CSE (DAT516, DIT515)
Version 20241106
Aarne Ranta
Notice: these slides give just some highlights. The material we will mainly focus on is the Python tutorial, from https://docs.python.org/3/tutorial/controlflow.html till the end.
Tutorial, Chapter 4, More Control Flow Tools
4.1 if statements
4.2 for statements
4.3 the range() function
https://docs.python.org/3/tutorial/controlflow.html
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
else:
print('Positive')
for w in words:
print(w, len(w))
for n in range(1, 11):
print(n ** 2)
sum(range(4))
list(range(10))
Tutorial 4.4-5: break, for-else, continue, pass
break exits the innermost loop
else in a loop runs when no break happens
continue jumps to the next iteration
pass: do nothing. Used when a statement is syntactically needed, often in a first version of a program.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through, no factor found
print(n, 'is a prime number')
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found an odd number", num)
while True:
pass
<condition>
<continuation>
<statement>
<statement>
False
True
while <condition>:
statement
…
statement
continuation
for x in <collection>:
#<condition>=<collection>
statement
…
statement
continuation
Control flow for loops
<condition>
<continuation>
<statement>
<statement>
False
True
while <condition>:
statement
…
break
statement
continuation
for x in <collection>:
#<condition>=<collection>
statement
…
break
statement
continuation
break
Control flow for loops
<condition>
<continuation>
<statement>
<statement>
False
True
while <condition>:
statement
…
continue
break
statement
continuation
for x in <collection>:
#<condition>=<collection>
statement
…
continue
break
statement
continuation
break
continue
Control flow for loops
<continuation>
<statement>
<statement>
False
True
while <condition>:
statement
…
continue
break
statement
else:
block
continuation
for x in collection:
# condition = collection
statement
…
continue
break
statement
else:
block
continuation
break
continue
else: <block>
<condition>
Control flow for loops
else
<continuation>
<statement>
<statement>
False
True
while <condition>:
statement
…
continue
break
return
statement
else:
block
continuation
for x in collection:
# condition = collection
statement
…
continue
break
return
statement
else:
block
continuation
break
continue
else: <block>
<condition>
return <exp>?
Control flow for loops
else, return
Tutorial 4.7: defining functions
(We skip 4.6, match, which is a new feature. It is similar to pattern matching (case) in Haskell.)
A function that just prints, and does not return.
A function that returns.
To think about: the type and value of
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(100)
def fib2(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
print(fib2(100))
Tutorial 4.8: more on defining functions
Default arguments
Default arguments must follow non-default arguments.
Related concept: keyword arguments.
The separators / can be used to separate different kinds of arguments. We will probably not need them, but they are useful to remember when reading APIs.
def topmost(xs, number=5):
return sorted(xs)[:number]
topmost([3, 4, 0, 0, 12, 5, 4, 8, 2])
topmost([3, 4, 0, 0, 12, 5, 4, 8, 2], number=3)
topmost([3, 4, 0, 0, 12, 5, 4, 8, 2], 3)
topmost(xs=[3, 4, 0, 0, 12, 5, 4, 8, 2])
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2)
Tutorial 4.8: arbitrary argument lists
The asterisk * means that any number of arguments can be given. They are treated as an iterable.
Conversely, an iterable can be given as an argument list
(The notation ** uses a dictionary to give values to keyword arguments. We may see this later when talking about dictionaries.)
def print_many(*args):
print('begin')
for arg in args:
print(' ', arg)
print('end')
print_many()
print_many('hello')
print_many(1, 2, 3)
print_many(*range(10))
Tutorial 4.8.6: lambda expressions
A function that just returns the value of an expression can be defined with a lambda expression.
Arbitrary argument lists work for lambda as well.
A typical usage: as sorting keys.
(we leave the rest, e.g. documentation strings, to your own reading)
def mean(x, y):
return (x+y)/2
mean(3, 8)
lmean = lambda x, y: (x+y)/2
lmean(3, 8)
mmean = lambda *xs: sum(xs)/len(xs)
mmean(3, 8, 10)
nums = list(range(10))
sorted(nums)
sorted(nums, key=lambda x: -x)
Tutorial 5: data structures
lists
dictionaries
tuples
sets
strings
ranges
[1, 2, 'hello', ['1', 2], 1]
{'se': 'Sweden', 'de': 'Germany'}
(1, 2, (3, 4))
{1, 2, 3}
'hello'
range(1, 11)
We will experiment with creating these objects, modifying them, and converting from one type to another.
Dictionaries will be in major role in Lecture 3; sets are also important.
Both sets and dictionaries have fast lookup. Lists are slower (with linear search). This is good to know if you have to use for instance the in operator.
See https://wiki.python.org/moin/TimeComplexity for the complexities.
Lists vs sets
Use lists if you want to
Use sets if you want to
A trick for removing duplicates from a list:
xs = list(set(xs))
However, this is not certain to preserve the order.
And it only works for lists of hashable elements, e.g. not for lists of lists (to be explained later).
Tutorial 5: more on conditions
chaining
conversion to boolean and value of operator
keeping your code simple
0 < x <= 10
[] or 'foo' or 'bar'
if (x < 10) == True:
return True
else:
return False
if (x < 10):
return True
else:
return False
return x < 10
Tutorial 6: modules
different ways of importing and what they make available
to show what it available in the module math
(skip for now: 6.4 Packages)
import math
math.cos(), math.sin()
import math as m
m.cos(), m.sin()
from math import cos
cos() # but not sin()
from math import cos, sin
cos(), sin()
from math import *
cos(), sin(), tan() # everything
dir(math)
Tutorial 7.1: string formatting
Many ways to produce this string
from these values
All have options for padding and rounding.
'the population of Sweden is 10402070'
country = 'Sweden'
pop = 10402070
'the population of ' + country + ' is ' + str(pop)
f'the population of {country} is {pop}'
'the population of {} is {}'.format(country, pop)
'the population of %(c)s is %(p)d' % {'c': country, 'p': pop}
Tutorial 7.2: reading and writing files
Recommended method: with blocks, which take care of closing the file.
(7.2.2 will be covered in Lecture 3)
with open(filename, 'r') as file:
for line in file:
print(len(line))
with open(filename, 'w') as file:
for x in range(100):
file.write(f'{x}\t{x**2}\n')
Tutorial 8.3: handling exceptions
Capturing an exception
Going more in depth requires knowledge of classes
(Tutorial 9: classes in lectures 5,6)
try:
x = int(input("Please enter a number: "))
except ValueError:
print("That was no valid number. Try again")
Tutorial 10: standard library
- sys, system: argv command line arguments
- math, mathematical functions: sin(), cos(), pi
- random: choice(), randrange()
- statistics: mean(), median()
- urllib, accessing the internet: urlopen()
- timeit, measuring the time to perform a computation: timeit()
- collections: deque()
- json, to structure and store data in files
- csv, to read and write files with comma-separated data (or tab-separated)
- xml.etree.ElementTree, to read and write XML data (in an extralab)
To do after this lecture
Read the official Python tutorial from Chapter 4 to the end
Test all examples in the tutorial
Read course lecture notes, Chapters 1-3
Do ex01 in the course GitHub, exercises/ (actually old intro course exam questions) if you feel at all uncertain about mastering the intro course contents