Python Introductory Course

Welcome to day 2:

  • Module, Imports, Packages
  • Complex Data Types, (Lists & Tuples), asymptotics
  • Sorting & List Comprehension
  • Control structures II (loops: break & continue, select-case meme)
  • Classes II (Inheritance)

Presenter Notes

Python Modules

  • So far we looked into small code examples from a single file
  • Putting all code in one file is just not modular
  • We want to encapsulate code that belongs together into one file
  • We want to be able to use this code from other places
  • We want to group several such modules into a package

Presenter Notes

Python Modules

File my_module.py:

1module_name = "my_module"
2
3def my_fancy_function():
4    print("this is fancy")
5
6class MyClass:
7    def __init__(self):
8        print("Congrats: You initialized a very cool object")

File main.py:

1from my_module import MyClass as MyAlias
2import my_module.my_fancy_function
3
4mc = MyAlias()
5my_module.my_fancy_function()

Presenter Notes

Python Modules Import

  • Using code from module requires prior import
  • You may alias what you import with a different name using as
  • E.g. you often see: import numpy as np
  • What can be imported? Classes, functions, constants, etc...
  • There are a lot of standard modules that come with usual python installs:

Presenter Notes

Exercises : Day 2 - 1

Use the python standard modules sys, os, math to:

  • display the version of your current python interpreter
  • get the number of CPUs installed in your system
  • get the absolute path of your current working directory
  • print names of and count all files in a root directory of your choice and within any sub-folder
  • calculate the following numbers:

\[ \sin^2 (\pi / 3), \left ( \begin{matrix} 10 \\ 5 \end{matrix} \right ) \]

Presenter Notes

Python Packages

  • You may group several of your modules into a python package
  • From the manual: "You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system."
  • A package is composed of one or several modules and an __init__.py file that marks the directory as a package
  • Packages may be composed of sub-packages (sub-directories)

Presenter Notes

Python Packages

A package "parent" containing three sub-packages:

 1parent/
 2    __init__.py
 3    parent.py
 4    one/
 5        __init__.py
 6        one.py
 7    two/
 8        __init__.py
 9        two.py
10    three.py

Now you can import like:

1from parent.one.one import one_function
2import parent.three
3import parent.two.two as ptwo

Presenter Notes

Complex Data Types: Lists II

Recap:

  • collection of elements
  • dynamic (size not defined from beginning)
  • implements iterator protocol (for elem in [1,2,3])
  • kind of slow!
  • if speed is a matter of concern use other data type!

Presenter Notes

Complex Data Types: List Asymptotics

https://peps.python.org/pep-3128/#motivation

Landscape

Presenter Notes

Lists: Sorting

Possibility 1: [list].sort()

  • ascending sort inplace
  • add keyword parameter reverse=True for descending
  • returns None
  • sort by key=

Possibility 2: Python builtin sorted

  • takes any iterable
  • returns the sorted iterable
  • also features reverse= and key=

Presenter Notes

Lists: Sorting

How to sort these?:

  • complex entries like (x, y) by x or y or x*y
  • not by elements, but by a function evaluated on elements
  • list of lists according to 3rd element: [[_, _, <sort_by_this>], [_, _, <sort_by_this>] ...]

  • The key is the key named parameter

  • You can pass a function that evaluates on an entry here

Presenter Notes

Lists: Sorting

Examples:

1arr = [-2.4, 3.8, 1.2, 0.0]
2arr.sort(key=abs)
3>>> [0.0, 1.2, -2.4, 3.8]
4
5from operator import itemgetter as getit
6arr = [(0,2), (1,4), (2,-3), (-3, 0)]
7print(sorted(arr, key=getit(1)))
8>>> [(2, -3), (-3, 0), (0, 2), (1, 4)]

Presenter Notes

Lists : enumeration

iterables can be enumerated using enumerate(iterable)

• useful if we are actually also interested in the indices apart from values

1list(enumerate(["zero", "one", "two"]))
2>>> [(0, 'zero'), (1, 'one'), (2, 'two')]
3
4for (idx, elem) in list(enumerate(["zero", "one", "two"])):
5    print("{}: {}".format(idx, elem))
6>>> 0: zero
7>>> 1: one
8>>> 2: two

Presenter Notes

Lists: operator.itemgetter

 1>>> help(operator.itemgetter)
 2Help on class itemgetter in module operator:
 3
 4class itemgetter(builtins.object)
 5 |  itemgetter(item, ...) --> itemgetter object
 6 |  
 7 |  Return a callable object that fetches the given item(s) from its operand.
 8 |  After f = itemgetter(2), the call f(r) returns r[2].
 9 |  After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
10 ...

Presenter Notes

Lists: Comprehension

Frequent Tasks involving lists:

• Ad hoc small list to iterate over

• Contitional subset of a larger list

Use List Compehension:

As filter:

1newlist = [expression for item in iterable if condition == True]

As manipulator:

1newlist = [expression(item) if condition(item) else other_expression(item) for item in iterable]

Presenter Notes

Lists: Comprehension Example 1

 1# fruits that contain an 'a' character
 2fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
 3newlist = []
 4
 5for x in fruits:
 6    if "a" in x:
 7        newlist.append(x)
 8
 9# with list comprehension this becomes:
10newlist = [f for f in fruits if 'a' in f]

Presenter Notes

Exercises : Day 2 - 2

  • create a list of (x, sin(x)) tuple values for N=20 stuetzstellen in the interval [0, 2*PI)
  • sort this list according to the values of the sine function
  • create a list with 40 elements of random strings with 5 letters (Hints: use string.ascii_letters and random.randint)
  • filter out strings containing the letter 'A' with list comprehension

Presenter Notes

Basic Control Structures II - Continued

More to loop control: Stopping in the middle

Single Loop:

  • break: step out of current loop and stop looping
  • often used like "found the item I want to manipulate - skip all the following items"
  • saves computation time
  • continue: step out of current loop step but continue the loop

Nested Loop:

  • more complicated, no --break-- to go back to outer loop
  • we may use a local function for inner loop (alternatively an exception)

Presenter Notes

Basic Control Structures II - Continued

Examples:

 1# basic example using break
 2for i in range(5):
 3    if i == 3:
 4        break
 5    print(i, end=" ")
 6
 7# basic example using continue
 8for i in range(5):
 9    if i == 3:
10        continue
11    print(i, end=" ")

Presenter Notes

Basic Control Structures - Conditionals III

if-else clause, generic example:

1if <some condition>:
2    print("some condition is TRUE")
3    break # we might break here if conditions are mutual exclusive
4elif <other condition>:
5    print("another condition is TRUE")
6elif <yet another condition>:
7    print("yet another condition is TRUE")
8else:
9    print("Everything above has evaluated to FALSE")

can be used to emulate a select-case type of behaviour known from other languages

Presenter Notes

Exercises : Day 2 - 3

  • Loop over the items of the following nested list (3d matrix) and find the element with value 6: matrix3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]. Write a function for doing so which returns the value and stops the iteration when found.
  • Adapt the looping and instead of returning the value, return the tuple of indices (x,y,z) corresponding to value 6

Presenter Notes

Classes II - Inheritance

Landscape

Presenter Notes

Classes II - Inheritance

  • Behavior and functionality is separated between parent (base) and child class

    • More general in parent class
    • More specific in child class
  • Implicitly a class inherits for Python's object cf. <YourClass>.__bases__

  • Python allows multiple intheritance (several parent classes)

Presenter Notes

Classes II - Inheritance

  • Behavior and functionality is separated between parent (base) and child class
  • More general in parent class
  • More specific in child class
  • Children inherit general behaviour and functionality from base
  • Children may extend or modify behaviour and functionality

Presenter Notes

Inheritance - Syntax & Simple Example

 1class Vehicle:
 2    def __init__(self):
 3        self._capacity = None
 4        self._num_passengers = None
 5
 6    def is_full(self):
 7        if self._num_passengers == self._capacity:
 8            return True
 9        else:
10            return False
11
12class Car(Vehicle):
13    def __init__(self):
14        super(Car, self).__init__()  # cf. in a second ...
15        self._capacity = 5

Presenter Notes

Classes II - Inheritance Pattern

Landscape

Presenter Notes

Inheritance - Method Overriding

 1class Car(Vehicle):
 2    ...
 3    def make_sound(self):
 4        print("wrooom")
 5
 6
 7class Bus(Vehicle):
 8    ...
 9    def make_sound(self):
10        print("ROOAAAARRRR")
11
12
13class ElectricCar(Car):
14    ...
15    def make_sound(self):
16        print("zzzzzzzzz")

Presenter Notes

Calling super

  • A child class is responsible for initializing itself
  • ... and its parent object(s)
  • Syntax: super(ClassName, self).__init__()
  • Call with appropriate arguments
  • also necessary to call methods of parent class in child classes

Presenter Notes

Inheritance Private Methods / Attributes

• as in other languages there is the concept of privacy

• private attributes / methods are not passed to child classes

• this is done by starting class member names with a double underscore (__)

• trying to access these from child class code will raise a AttributeError

 1class A:
 2    def __private_method(self):
 3        print("private method called")
 4
 5class B(A):
 6    def get_name(self):
 7        self.__private_method()
 8        print("get_name called")
 9
10b1 = B()
11b1.get_name()
12>>> AttributeError: 'B' object has no attribute '_B__private_method'

Presenter Notes

Presenter Notes