Welcome to this Workshop !

  • This workshop is brought to you by PTB's IT department (Q.4)
  • I work for the HPC department at PTB (Q.45)
  • I am a physicist (QCD), data analyst (DNA), software architect (HPC)

Landscape

Presenter Notes

Python Introductory Course

Welcome to day 1:

  • Python Intro (Philosophy, differences to other languages, "Hello World")
  • Syntax
  • Variables and scope (basic types, int, float, string, casts)
  • Control structures I (loops, conditions)
  • Basic IO (read, print)
  • Functions I
  • Classes I (Definition, constructor, members)

Presenter Notes

Python - What is it?

  • Focus on simplicity, readability and ease of use
  • Interpreted language (as opposed to compiled)
  • Widely adopted in many fields with large community and eco-system
  • Imperative, Object Oriented, Functional
  • Continuously developed, Current Version: v3.12 (3.13 in beta)

Presenter Notes

Question Round - Why are you here?

Presenter Notes

Python - What it is not?

  • fast
  • memory efficient
  • near to the hardware
  • a functional language

Presenter Notes

Where to get help

  • https://docs.python.org/3/index.html
  • Python's inbuilt documentation help(...)
  • https://www.w3schools.com/python/
  • StackOverflow

Presenter Notes

Python Basic Syntax

  • Code Blocks organized by indentation
  • i.e.: no begin-end stuff or brackets {}
  • Recommendations:
    • Use the same amount of <SPACE>s
    • Never mix <TAB> and <SPACE>
    • Use <TAB> to <SPACE>s conversion of your IDE / Editor

Presenter Notes

Python Basic Syntax

Example:

 1# <this is the first block>
 2    # we
 3    # indent
 4    # the same
 5    # until
 6        ## here the
 7        ## second intermediate
 8        ## block starts
 9    # and then
10    # we are back

And now with some actual code:

1class Foo:
2    def bar(self, x):
3    # this method is useful
4        return x + x*x
5
6    def barbar(self, x):
7    # this method is useful 2
8        pass

Presenter Notes

A Hello World Example in the Python Console

1>>> print("Hello World!")
2Hello World

Presenter Notes

Python Code Style

  • Python has Syntax rules: PEP8
  • https://peps.python.org/pep-0008/
  • if possible, stick with that as much as possible
  • modern IDEs (such as e.g. pyCharm) offer linters

Presenter Notes

Variables

  • store your data
  • ... and internal program state
  • have a scope (lifetime)
  • are objects (even the basic types)
  • ... this has implications
  • we can get the type of a variable using: type(variable)

Presenter Notes

Variables: Basic types

  • int (integer numbers, e.g. 42)
  • float (floating point numbers, e.g. 3.14159)
  • str (character strings, e.g. "Python allows us to produce maintainable features in record times, with a minimum of developers", Cuong Do (Software Architect, YouTube.com) )
  • bool (boolean value, True or False)
  • special: None (like "not ininitialized" but "there")
  • Conversions possible using int(), float(), str() methods

Presenter Notes

Variables: Basic types, Instantiation

 1# int variable
 2a = 10
 3
 4# float variable
 5f = 1.456
 6
 7# string
 8s = "hello"
 9
10# None
11not_yet = None

Presenter Notes

Exercises : Day 1 - 1

  • Open PyCharm and create a new project
  • Find the "Python Console"
  • Create variables of the 4 basic types and one containing None
  • On the numeric types, do some basic math operations and verify the results
  • Create an empty and a filled str type variable
  • Try to convert them into one another, see what comes out
  • Consider and try to understand this: bool(10) + bool(None) + 1.0

Presenter Notes

Variables: Scope I

function scope:

1# outer scope
2a = 9
3def my_fun():
4    # inner scope
5    a = 10
6    print(a)
7
8my_fun() # 10
9print(a) #  9

Presenter Notes

Variables: Scope II

with global keyword:

1# outer scope
2a = 9
3def my_fun():
4    # inner scope
5    global a = 10
6    print(a)
7
8my_fun() # 10
9print(a) # 10

NOTE: NOT recommended!

Presenter Notes

Variables: Scope III

No block scope:

1# outer scope
2i = 15
3if i > 10:
4    # inner scope
5    i = 9
6print(i) # 9

Presenter Notes

Variables: Lists

  • ordered structure of elements
  • elements can be of different type
  • can be iterated over c.f. loops chapter
  • are "mutable" (in comparison to tuples)
  • think of them as dynamic ordered collection of elements

Presenter Notes

Variables: List Example

 1# different element types
 2mixed_list = [1, 1.0, "Eins", '1']
 3
 4# length
 5len(mixed_list)
 6>>> 4
 7
 8# same element types
 9int_list = [1, 2, 3, 4, 5, 6, 7]
10print(int_list)
11>>> [1, 2, 3, 4, 5, 6, 7]
12
13# indexing
14int_list[0]  # Note: In python index 0 is the first!
15>>> 1
16
17# slicing
18int_list[1:3]
19>>> [2, 3]
20
21# access from the end
22int_list[-1]
23>>> 7

Presenter Notes

Variables: List Functionality

  • Sorting (sort) [inplace]
  • Appending elements (append(<elem>))
  • Reverse (reverse()) [inplace]
  • Indexing, Slicing
  • Count elements with value (count(<value>))
  • Length (len(<list>))

Presenter Notes

List - Methods

Landscape

Presenter Notes

Exercises : Day 1 - 2

  • create a random list of int with 10 elements, e.g. [2, 6, 9, 13, 9, 45, 1, 16, 12, 32]
  • take elements 4-6 (3 elements in total, indexing starts at 0!) out and put them into a new list
  • ... sort this list
  • ... and add it to the back of the original list
  • Variation I: do the same, but remove the taken out elemnents from the original list
  • Variation II: do the same but take 3 elements starting from the minimum value in the list. Use above example list for that!

Presenter Notes

Variables: Tuples

  • ordered structure of elements
  • elements can be of different type
  • can be iterated over c.f. loops chapter
  • are "immutable" in comparison to lists
  • Think of them as fixed ordered collection of elements

Examples:

1p_x = 1
2p_y = 3
3my_point = (p_x, p_y)

Presenter Notes

Basic Control Structures - Conditionals I

if-clause generic example:

1if <some condition>:
2    print("some condition is TRUE")

Examples for <some condition>:

a == b

a > 15 and b < 10

a is None

isinstance(a, int)

a

Presenter Notes

Basic Control Structures - Conditionals II

if-else clause, generic example:

1if <some condition>:
2    print("some condition is TRUE")
3else:
4    print("some condition is FALSE")

<some condition> is met: → Block below if is executed

in all other cases → Block below else is executed

Presenter Notes

Basic Control Structures - Conditionals III

Comparison Operations:

Landscape

Presenter Notes

Basic Control Structures - Conditionals VI

Logical Operations:

Landscape

Every other Operator is constructible from above set.

Presenter Notes

Exercises : Day 1 - 3

Implement the following program:

Landscape

Presenter Notes

Basic Control Structures - Loops I

Preface:

  • loops are where your program will spend most of CPU time
  • different kinds possible:
    • over a fixed integer interval
    • with strides
    • over elements of some objects
    • as long as a condition is true
  • Can be nested
  • Inner loops can have dependencies
  • We can step out a loop with break

Presenter Notes

Basic Control Structures - Loops II

Fixed length for loop:

\[ i \in [ 0, 1, \ldots , N - 1 ] \]

1N = 15
2for i in range(N):
3    print(i)

Presenter Notes

Basic Control Structures - Loops II

while ... do:

1N = 15
2i = N
3while i > 0:
4    print(i)
5    i -= 1

do ... while:

can only be emulated in Python...

1N = 15
2i = N
3while True:
4    print(i)
5    i -= 1
6    if i == 0:
7        break

Presenter Notes

Basic Control Structures - Loops III

over elements (of lists, tuples etc.):

1languages = ["C", "C++", "Python", "Golang"]
2for l in languages:
3    print(l, end=" ")
4    print("is a nice programming language")

Presenter Notes

Basic Control Structures - Loops III

How does this actually work?

  • loop over elements works via an "iterator"
  • ... as the range function returns
  • "magic method" (cf. day 4)
  • iterator method successively returns "next" value
  • invoked by in
  • python iterable objects (lists, tuples, dicts etc.)

Presenter Notes

Exercises : Day 1 - 4

Implement the following matrix-vector multiplication:

\[ \left ( \begin{matrix} 0.0 & -0.5 & 0.866 \\ 0.707 & -0.612 & -0.354 \\ 0.707 & 0.612 & 0.354 \\ \end{matrix} \right ) * \left ( \begin{matrix} 0.5774 \\ 0.5774 \\ 0.5774 \\ \end{matrix} \right ) \]

Up to roundoff as well as tutor errors this is the result of consecutive rotation of a unit vector in [ (1, 1, 1) ] direction by $$ \frac{\pi}{2}, - \frac{\pi}{4}, \frac{\pi}{3} $$ around the z, y, x-axes, respectively. ( x then y then z)

Presenter Notes

Functions - The Basics

  • functions encapsulate a single functionality
  • crucial for reusability
  • take arguments via an argument list
  • may return something
  • even if a function returns nothing it actually returns None

Presenter Notes

Functions - Examples

Example:

1def add(s1, s2):
2    return s1 + s2
3
4print(add(1, 3))
5>>> 4

General Syntax:

1def function_name_snake_case(arg1, arg2, ..., arg_with_default1=<val1>, arg_with_default2=<val2>, ...):
2    # function body
3    pass # temporarily pass over this function

Presenter Notes

Functions - Arguments

  • generally two different kinds of arguments
  • required: arg1, arg2, ...
  • optional: arg_with_default1, arg_with_default2,...
  • optional arguments come after required arguments
  • use sensible parameter names

Presenter Notes

Functions - Argument passing

• simple types: by value

• complex types, object instances: by reference

• arguments passed by position and / or by name (keyword):

 1def my_fun(a, b, c=0.0):
 2    return a * b + c
 3
 4# positional
 5my_fun(1., 2., 3.0)
 6
 7# keyword
 8my_fun(a=2.0, b=2.0, c=-4.0)
 9
10# mix - possible, yet this is a mess!
11my_fun(2.0, c=1.0, b=1.0)

Presenter Notes

IO - printing variables

  • print
  • ... we already saw some of it above
  • takes arbitrary number of args, e.g. print(5, " is a number, that is different from ", 5.0)
  • separation and line end character can be passed

Presenter Notes

IO - string format

Best explained with examples:

 1print("{} is a very cool concept".format("string formatting"))
 2>>> "string formatting is a very cool concept"
 3
 4a = 1; b = 2
 5print("{b} is larger than {a}".format(a=a, b=b))
 6>>> "2 is larger than 1"
 7
 8fp_zahl = 1.2348343846284654
 9print("{num:.4f}".format(num=fp_zahl))
10>>> 1.2348
11
12# format string literals
13our_language = "Python"
14print(f'{our_language} is quite awesome')
15>>> "Python is quite awesome"

There is also an old and deprecated way using %s

Presenter Notes

IO - User Input

1your_name = input("please enter your name")
2print(your_name)

You will most likely never use this in real world :D

Presenter Notes

Exercises : Day 1 - 5

• First stand-alone exercise - Use a new .py file

• Write a function that returns the Fibonacci sequence F(n)

• Read the integer n from user and print the resulting F(n)

 1def F(n):
 2    pass
 3
 4if __name__ == "__main__":
 5
 6    # read user input for n
 7
 8    fib = F(n)
 9
10    # print the result fib

\[ F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) \]

Presenter Notes

Classes - OOP Outline

  • in Object Oriented Programming ...
  • ... the class is the blueprint for the object
  • Objects encapsulate aspects (properties) and functionality (methods) of entities
  • Inheritance: child-objects inherit from and specialize parent object
  • How to do this wisely? → advanced course

Presenter Notes

Classes - OOP Outline

Landscape

Presenter Notes

Classes - Definition

1class Person:
2    species = "Homo Sapiens" # class attribute
3
4    def __init__(self, name, age):
5      self.name = name  # instance attribute
6      self.age = age    # instance attribute
7
8    def has_birthday(self):
9        self.age += 1

Presenter Notes

Classes - The __init__ method

• is called to construct an instance of the class

• gets passed all information to properly initialize the object

 1# instantiation of a Person
 2alice = Person("Alice", 42)
 3
 4# instantiation of another Person
 5bob = Person("Bob", 27)
 6
 7print(bob.name)
 8>>> "Bob"
 9print(bob.age)
10>>> 27
11bob.has_birthday()
12print(bob.age)
13>>> 28

Presenter Notes

Presenter Notes