1 of 23

Continuation Course in Programming in Python

Lecture 2:

Python recap and tutorial II

Chalmers/GU CSE (DAT516, DIT515)

Version 20241106

Aarne Ranta

2 of 23

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.

3 of 23

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))

4 of 23

Tutorial 4.4-5: break, for-else, continue, pass

break exits the innermost loop

  • to test: what happens if you move break to another place

else in a loop runs when no break happens

  • to test: is elif possible?

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

5 of 23

<condition>

<continuation>

<statement>

<statement>

False

True

while <condition>:

statement

…

statement

continuation

for x in <collection>:

#<condition>=<collection>

statement

…

statement

continuation

Control flow for loops

6 of 23

<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

  • with break

7 of 23

<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

  • with break or continue

8 of 23

<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

  • with break, continue,

else

9 of 23

<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

  • with break, continue,

else, return

10 of 23

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.

  • The function must be called to see a result.
  • The type of fib is function.

A function that returns.

  • The call of the function must be printed to see a result

To think about: the type and value of

  • fib, fib2, fib(100), fib2(100)

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))

11 of 23

Tutorial 4.8: more on defining functions

Default arguments

  • need not be given in function calls
  • but can be overridden

Default arguments must follow non-default arguments.

Related concept: keyword arguments.

  • even non-default arguments can be called in this way, by mentioning their variables

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)

12 of 23

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))

13 of 23

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.

  • quiz: what is the default value of key ?

(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)

14 of 23

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)

15 of 23

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.

16 of 23

Lists vs sets

Use lists if you want to

  • maintain order
  • maintain repetitions
  • add new elements quickly

Use sets if you want to

  • ignore repetitions
  • look up elements quickly

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).

17 of 23

Tutorial 5: more on conditions

chaining

conversion to boolean and value of operator

  • what do you think is the value ?

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

18 of 23

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)

19 of 23

Tutorial 7.1: string formatting

Many ways to produce this string

from these values

  1. gluing with +

  • f-string

  • the format() method

  • the % operator (C style)

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}

20 of 23

Tutorial 7.2: reading and writing files

Recommended method: with blocks, which take care of closing the file.

  • 'r' for 'reading' is optional

(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')

21 of 23

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")

22 of 23

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)

23 of 23

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