SlideShare a Scribd company logo
3/4/2023
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Slide 17
Numerical Data Types
int : integer numbers (infinite)
float : corresponds to double in C
complex : complex numbers ( j is the imaginary unit)
a = 1
c = 1.0
c = 1e0
d = 1 + 0j
Slide 18
Operators on Numbers
Basic arithmetics: + , - , * , /
hint: Python 2 ⇒ 1/2 = 0
Python 3 ⇒ 1/2 = 0.5
Div and modulo operator: // , %, divmod(x, y)
Absolute value: abs(x)
Rounding: round(x)
Conversion: int(x) , float(x) , complex(re [ , im=0])
Conjugate of a complex number: x.conjugate()
Power: x ** y , pow(x, y)
Result of a composition of different data types is of the “bigger” data type.
Slide 19
Bitwise Operation on Integers
Operations:
AND: x &y
OR: x | y
exclusive OR (XOR) :
x ˆ y
invert: ~x
shift right n bits: x >> n
shift left n bits: x << n
Use bin(x) to get binary
representation string of x .
>>> pr i nt ( bi n( 6) , bi n( 3) )
0b110 0b11
>>> 6 & 3
2
>>> 6 | 3
7
>>> 6 ^ 3
5
>>> ~0
-1
>>> 1 << 3
8
>>> pow( 2, 3)
8
>>> 9 >> 1
4
>>> pr i nt ( bi n( 9) , bi n( 9>>1) )
0b1001 0b100
Slide 20
3/4/2023
Strings
Data type: str
s = ’spam’ , s = "spam"
Multiline strings: s = """spam"""
s = r"spnam"
str(1.0)
No interpretation of escape sequences:
Generate strings from other data types:
>>> s = """hello
... world"""
>>> pr i nt ( s )
h e l l o
world
>>> pr i nt ( " sp nam
" )
sp
am
>>> pr i nt ( r " spnam" ) # or: print("spnam")
spnam
Slide 21
String Methods
Count appearance of substrings: s.count(sub [ , start[, end]])
Begins/ends with a substring? s.startswith(sub[, start[, end]]) ,
s.endswith(sub[, start[, end]])
All capital/lowercase letters: s.upper() , s.lower()
Remove whitespace: s.strip([chars])
Split at substring: s.split([sub [,maxsplit]])
Find position of substring: s.index(sub[, start[, end]])
Replace a substring: s.replace(old, new[, count])
More methods: help(str) , dir(str)
Slide 22
Lists
Data type: l i s t
s = [1, "spam", 9.0, 42] , s = [ ]
Append an element: s.append(x)
Extend with a second list: s.extend(s2)
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Insert element at position: s.insert(i, x)
Remove and return element at position: s.pop([i])
Delete element: s.remove(x)
Reverse list: s.reverse()
Sort: s.sort([cmp[, key[, reverse]]])
Sum of the elements: sum(s)
Slide 23
Tuple
Data type: tuple
s = 1, "spam", 9.0, 42
s = (1, "spam", 9.0, 42)
Constant list
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Sum of the elements: sum(s)
Slide 24
3/4/2023
Tuple
Data type: tuple
s = 1, "spam", 9.0, 42
s = (1, "spam", 9.0, 42)
Constant list
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Sum of the elements: sum(s)
Multidimensional tuples and lists
List and tuple can be nested (mixed):
>>> A=( [ 1, 2, 3] , ( 1, 2, 3) )
>>> A
( [ 1, 2, 3] , ( 1, 2, 3) )
>>> A[ 0] [ 2] =99
>>> A
( [ 1, 2, 99] , ( 1, 2, 3) )
Slide 24
Lists, Strings and Tuples
Lists are mutable
Strings and tuples are immutable
No assignment s [ i ] = . . .
No appending and removing of elements
Functions like x.upper() return a new string!
>>> s 1 = " s pam"
>>> s 2 = s1. upper ( )
>>> s1
’ s pam’
>>> s2
’ SPAM’
Slide 25
Operations on Sequences
Strings, lists and tuples have much in common: They are sequences.
Does/doesn’t s contain an element?
x in s , x not in s
Concatenate sequences: s + t
Multiply sequences: n * s , s * n
i-th element: s [ i] , i-th to last element: s [ - i ]
Subsequence (slice): s [ i : j ] , with step size k: s [ i : j : k ]
Subsequence (slice) from beginning/to end: s [ : - i ] , s [ i : ] , s [ : ]
Length (number of elements): len(s)
Smallest/largest element: min(s) , max(s)
Assignments:
→ a = s[0] ,
(a , b, c) = s
b = s[1] , c = s[2]
Slide 26
Indexing in Python
positive index 0 1 2 3 4 5 6 7 8 9 10
element P y t h o n K u r s
negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> kur s = " Pyt hon Kur s "
>>> kur s [ 2: 2]
>>> kur s [ 2: 3]
t
>>> kur s [ 2]
t
>>> kur s [ - 4: - 1]
Kur
>>> kur s [ - 4: ]
Kurs
>>> kur s [ - 6: - 8: - 1]
no
Slide 27
3/4/2023
Boolean Values
Data type bool: True , False
Values that are evaluated to False :
None (data type NoneType )
False
0 (in every numerical data type)
Empty strings, lists and tuples: ” , [ ] , ()
Empty dictionaries: {}
Empty sets set()
All other objects of built-in data types are evaluated to True !
>>> bool ( [ 1, 2, 3] )
True
>>> b o o l ( " " )
F al se
Slide 28
References
Every object name is a reference to this object!
An assignment to a new name creates an additional reference to this object.
s2 = s1[:]
Hint: copy a list with or s2 = list(s1)
Operator is compares two references (identity),
==
operator compares the contents of two objects
Assignment: different behavior depending on object type
Strings, numbers (simple data types): create a new object with new value
Lists, dictionaries, ...: the original object will be changed
Slide 29
Reference - Example
>>> x=1
>>> y=x
>>> x i s y
True
>>> y=2
>>> x i s y
False
x
1
Slide 30
Reference - Example
>>> x=1
>>> y=x
>>> x i s y
True
>>> y=2
>>> x i s y
False
x
y
1
Slide 30
3/4/2023
Reference - Example
>>> x=1
>>> y=x
>>> x i s y
True
>>> y=2
>>> x i s y
False
x
y
1
2
Slide 30
Reference - Example
>>> x=1
>>> y=x
>>> x i s y
True
>>> y=2
>>> x i s y
False
x
y
1
2
>>> s1 = [ 1, 2, 3, 4]
>>> s2 = s1
>>> s2[1] = 17
>>> s1
[ 1, 17, 3, 4]
>>> s2
[ 1, 17, 3, 4]
1
2
3
4
s1
s2
Slide 30
Reference - Example
>>> x=1
>>> y=x
>>> x i s y
True
>>> y=2
>>> x i s y
False
x
y
1
2
>>> s1 = [ 1, 2, 3, 4]
>>> s2 = s1
>>> s2[1] = 17
>>> s1
[ 1, 17, 3, 4]
>>> s2
[ 1, 17, 3, 4]
1
17
3
4
s1
s2
Slide 30
Groups
1 2 3 4
5 6 7 8
Slide 31
3/4/2023
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Slide 32
The If Statement
i f a == 3:
pr i nt ( " Aha ! " )
Blocks are defined by indentation! ⇒Style Guide for Python
Standard: Indentation with four spaces
i f a == 3:
pr i nt ( " s pam" )
e l i f a == 10:
pr i nt ( " eggs " )
e l i f a == - 3 :
pr i nt ( " bac on" )
el s e :
pr i nt ( " s om
et hi ng el s e " )
Slide 33
Relational Operators
Comparison of content: == , < , > , <= , >= , !=
Comparison of object identity: a is b , a is not b
And/or operator: a and b , a or b
Chained comparison: a <= x < b , a == b == c , .. .
Negation: not a
i f not ( a==b) and ( c <3) :
pass
pass
Hint: is a No Operation (NOOP) function
Slide 34
For Loops
fo r i in range ( 1 0 ) :
pr i nt ( i ) # 0, 1, 2, 3, ..., 9
f or i i n r ange ( 3, 10) :
pr i nt ( i ) # 3, 4, 5, ..., 9
f or i i n r ange ( 0, 10, 2) :
pr i nt ( i ) # 0, 2, 4, 6, 8
el s e :
pr i nt ( " Loop c om
pl et ed. " )
End loop prematurely: break
Next iteration: continue
else is executed when loop didn’t end prematurely
Slide 35
3/4/2023
For Loops (continued)
Iterating directly over sequences (without using an index):
f or i t em i n [ " s pam" , " eggs " , " bac on" ] :
p r i n t ( item )
range
The function can be used to create a list:
>>> l i s t ( r ange ( 0, 10, 2) )
[ 0, 2, 4, 6, 8]
If indexes are necessary:
f or ( i , c har ) i n enum
er at e( " hel l o wor l d" ) :
p r i n t ( i , c har)
Slide 36
While Loops
i = 0
while i < 10:
i += 1
break continue
and work for while loops, too.
Substitute for do-while loop:
whi l e Tr ue :
# important code
i f c ondi t i on:
break
Slide 37
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Functions
def add( a, b) :
"""Returns the sum of a and b."""
mysum= a + b
return mysum
>>> r es ul t = add( 3, 5)
>>> pr i nt ( r es ul t )
8
>>> hel p( add)
Help on fun c ti o n add in module _ _ m a i n _ _ :
add( a, b)
Returns the sum o f a and b .
3/4/2023
Return Values and Parameters
Functions accept arbitrary objects as parameters and return values
Types of parameters and return values are unspecified
Functions without explicit return value return None
my_program.py
def hel lo _ wo rl d ( ) :
pr i nt ( " Hel l o W
or l d! " )
a = hel l o_ wor l d( )
pr i nt ( a)
$ pyt hon3 m
y_ pr ogr am
. py
Hel l o W
or l d!
None
Multiple Return Values
Multiple return values are realised using tuples or lists:
def f oo( ) :
a = 17
b = 42
return ( a , b)
r et = f oo( )
( x , y) = f oo( )
Optional Parameters – Default Values
Parameters can be defined with default values.
Hint: It is not allowed to define non-default parameters after default parameters
plot_lines.py
def f l i ne ( x, m
=1, b=0) : # f(x) = m*x + b
r et ur n m
* x + b
fo r i in range ( 5 ) :
pr i nt ( f l i ne ( i ) , end=" " )
#force newline
pr i nt ( )
fo r i in range ( 5 ) :
pr i nt ( f l i ne ( i , - 1, 1) , end=" " )
$ pyt hon3 pl ot _ l i nes . py
0 1 2 3 4
1 0 -1 -2 -3
end
Hint: in print defines the last character, default is linebreak
Positional Parameters
pr i nt ( " Per s on:
pr i nt ( " Age :
" , nam
e )
" , age , " year s " )
Parameters can be passed to a function in a different order than specified:
displayPerson.py
def pr i nt Cont ac t ( nam
e , age , l oc at i on) :
pr i nt ( " Addr es s : " , l oc at i on)
p r i n t C o n t a c t ( name=" Peter Pan" , l o c a t i o n =" Neverland " , age =10)
$ pyt hon3 di s pl ayPer s on. py
Per s on:
Age:
Peter Pan
10 years
Address: Neverland
3/4/2023
Functions are Objects
Functions are objects and as such can be assigned and passed on:
>>> a = f l o a t
>>> a ( 22)
22.0
>>> def f oo( f kt ) :
. . . pr i nt ( f kt ( 33) )
. . .
>>> f oo( f l oat )
33.0
>>> f oo( s t r )
33
>>> f oo( c om
pl ex)
( 33+0j )
Online Help: Docstrings
Can be used in function, modul, class and method definitions
Is defined by a string as the first statement in the definition
hel p (. ..) on python object returns the docstring
Two types of docstrings: one-liners and multi-liners
def c om
pl ex( r eal =0. 0, i m
ag =0. 0) :
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
. . .
Functions & Modules
Functions thematically belonging together can be stored in a separate Python file.
(Same for objects and classes)
This file is called module and can be loaded in any Python script.
Multiple modules available in the Python Standard Library
(part of the Python installation)
import <filename>
Command for loading a module:
(filename without ending .py)
import math
s = m
at h. s i n( m
at h. pi )
More information for standard modules and how to create your own module see chapter
Modules and Packages on slide 91
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
3/4/2023
String Formatting
Format string + class method x.format()
“replacement fields”: curly braces around optional arg_name (default: 0,1,2,...)
pr i nt ( " The ans wer i s { 0: 4d} " . f or m
at ( 42) )
’ The ans wer i s 42’
s = " { 0 } : {1 :08 . 3 f } " . fo rmat( " spam" , 3. 14)
’ s pam: 0003. 140’
format purpose
default: string
m.nf floating point: m filed size, n digits after the decimal point (6)
m.ne floating point (exponential): m filed size, 1 digit before and n digits behind the
decimal point (default: 6)
m.n% percentage: similar to format f, value ∗
100 with finalizing ’%’
md Integer number: m field size (0m ⇒leading “0”)
format d can be replaced by b (binary), o (octal) or x (hexadecimal)
Literal String Interpolation (f-strings)
Provides a way to embed expressions inside string literals, using a minimal syntax
Is a literal string, prefixed with ’f’, which contains expressions inside braces
Expressions are evaluated at runtime and replaced with their values.
>>> nam
e = " Mar t i n"
>>> age = 50
>>> f " My name i s { name} and my age next year i s { age +1}"
’ Myname i s Martin and myage next year i s 51’
>>> val ue = 12. 345
>>> f " val ue ={ val ue : 5. 2f } "
’ val ue =12. 35’
Hint: Since Python 3.6!
String Formatting (deprecated, Python 2 only)
String formatting similar to C:
pr i nt " The ans wer i s %
4i . " % 42
s = " %
s : %
08. 3f " % ( " s pam" , 3. 14)
Integer decimal: d, i
Integer octal: o
Integer hexadecimal: x, X
Float: f, F
Float in exponential form: e, E, g, G
Single character: c
String: s
Use %
%to output a single %character.
Command Line Input
User input in Python 3:
us er _ i nput = i nput ( " Type s om
et hi ng: " )
User input in Python 2:
us er_ i npu t = raw _ inp ut(" Type something : " )
Hint: In Python 2 is input("...") ⇐⇒ eval(raw_input("..."))
Command line parameters:
params.py
import sys
pr i nt ( s ys . ar gv)
$ pyt hon3 par am
s . py
s pam[ ’ par am
s . py ’ , ’ spam’ ]
3/4/2023
Files
f i l e1 = open( " s pam. t xt " , " r " )
f i l e2 = open( " /t m
p/eggs . j s on" , " wb" )
Read mode: r
Write mode (new file): w
Write mode, appending to the end: a
Handling binary files: e.g. rb
Read and write (update): r+
f or l i ne i n f i l e1:
pr i nt ( l i ne )
Operations on Files
Read: f.read([size])
Read a line: f.readline()
Read multiple lines: f.readlines([sizehint])
Write: f.write(str)
Write multiple lines: f.writelines(sequence)
Close file: f.close()
f i l e1 = open( " t es t . t xt " , " w" )
l i nes = [ " s pamn" , " eggs n" , " hamn" ]
f i l e1. wr i t el i nes ( l i nes )
f i l e1. c l os e ( )
Python automatically converts n into the correct line ending!
The with statement
File handling (open/close) can be done by the context manager with .
(⇒section Errors and Exceptions on slide 65).
wi t h open( " t es t . t xt " ) as f :
fo r l i n e in f :
pr i nt ( l i ne )
with
After finishing the block the file object is closed, even if an exception occurred
inside the block.
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
3/4/2023
Syntax Errors, Indentation Errors
Parsing errors: Program will not be executed.
Mismatched or missing parenthesis
Missing or misplaced semicolons, colons, commas
Indentation errors
add.py
pr i nt ( " I ’ m r unni ng . . . " )
def add( a, b)
return a + b
$ pyt hon3 add. py
Fi l e " add. py" , l i ne 2
def add( a, b)
^
Synt axEr r or : i nval i d s ynt ax
Exceptions
Exceptions occur at runtime:
import math
pr i nt ( " I ’ m r unni ng . . . " )
m
at h. f oo( )
pr i nt ( " I ’ m s t i l l r unni ng. . . " )
error.py
$ pyt hon3 er r or . py
I ’ m r unni ng . . .
Tr ac ebac k ( m
os t r ec ent c al l l as t ) :
Fi l e " er r or . py" , l i ne 3, i n <m
odul e >
m
at h. f oo( )
A t t r i b u t e Error : module ’ math ’ has no a t t r i b u t e ’ f oo ’
Handling Exceptions (1)
t r y:
s = i nput ( " Ent er a num
ber : " )
num
ber = f l oat ( s )
exc ept Val ueEr r or :
pr i nt ( " That ’ s not a num
ber ! " )
except try
block is executed when the code in the block throws an according
exception
Afterwards, the program continues normally
Unhandled exceptions force the program to exit.
Handling different kinds of exceptions:
exc ept ( Val ueEr r or , TypeEr r or , Nam
eEr r or ) :
Built-in exceptions: http://docs.python.org/library/exceptions.html
Handling Exceptions (2)
t r y:
s = i nput ( " Ent er a num
ber : " )
num
ber = 1/ f l oat ( s )
exc ept Val ueEr r or :
pr i nt ( " That ’ s not a num
ber ! " )
exc ept Zer oDi vi s i onEr r or :
p r i n t ( " You can ’ t di vid e by zero ! " )
e x c e p t :
pr i nt ( " Oops , what ’ s happened? " )
except
Several statements for different exceptions
except
Last can be used without specifying the kind of exception: Catches all
remaining exceptions
Careful: Can mask unintended programming errors!
3/4/2023
Handling Exceptions (3)
else is executed if no exception occurred
finally is executed in any case
t r y:
f = open( " s pam
" ) except I OE rro r:
pr i nt ( " Cannot open f i l e " )
e l s e :
pr i nt ( f . r ead( ) )
f . c l os e ( )
f i nal l y:
pr i nt ( " End of t r y. " )
Exception Objects
Access to exception objects:
EnvironmentError ( IOError , OSError ):
int ,
Exception object has 3 attributes ( str , str )
Otherwise: Exception object is a string
spam_open.py
t r y:
f = open( " s pam
" ) except IOError as
e :
pr i nt ( e. er r no , e. f i l enam
e , e. s t r er r or )
p r i n t ( e)
$ pyt hon3 s pam
_ open. py
2 spam No such f i l e or d i r e c t o r y
[ Er r no 2] No s uc h f i l e or di r ec t or y: ’ s pam’
Exceptions in Function Calls
draw()
rectangle()
line() Exception!
Function calls another function.
That function raises an exception.
Is exception handled?
No: Pass exception to calling function.
Raising Exceptions
opening f i l e ! " )
Passing exceptions on:
t r y:
f = open( " s pam
" ) except I OE rro r:
pr i nt ( " Pr obl em whi l e
r a i s e
Raising exceptions:
def gaus s _ s ol ver ( m
at r i x) :
# Important code
r ai s e Val ueEr r or ( " Si ngul ar m
at r i x" )
3/4/2023
Exceptions vs. Checking Values Beforehand
Exceptions are preferable!
def s quar e( x ) :
i f t ype ( x) == i nt or t ype( x) == f l oat :
return x ** 2
el s e :
return None
What about other numerical data types (complex numbers, own data types)? Better:
Try to compute the power and catch possible exceptions! → Duck-Typing
Caller of a function might forget to check return values for validity. Better: Raise an
exception!
Slide 64
Exceptions vs. Checking Values Beforehand
Exceptions are preferable!
t ype ( x) == f l oat :
def s quar e( x ) :
i f t ype ( x) == i nt or
return x ** 2
el s e :
return None
def s quar e( x ) :
return x ** 2
. . .
t r y:
r es ul t = s quar e( val ue )
exc ept TypeEr r or :
pr i nt ( " ’ { 0} ’ : I nval i d t ype " . f or m
at ( val ue ) )
Slide 64
The with Statement
Some objects offer context management 3 , which provides a more convenient way to
try . . . finally
write blocks:
wi t h open( " t es t . t xt " ) as f :
fo r l i n e in f :
pr i nt ( l i ne )
with
After the block the file object is guaranteed to be closed properly, no matter what
exceptions occurred within the block.
exit ( . . . )
3
Class method enter ( sel f) will be executed at the beginning and class method
at the end of the context
Slide 65
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Slide 66
3/4/2023
Sets
Set: unordered, no duplicated elements
s = {"a", "b", "c"}
alternative s = set([sequence]) , required for empty sets.
Constant set: s = frozenset([sequence])
e.g. empty set: empty = frozenset()
Subset: s.issubset(t) , s <= t , strict subset: s < t
Superset: s.issuperset(t) , s >= t , strict superset: s > t
Union: s.union(t) , s | t
Intersection: s.intersection(t) , s & t
Difference: s.difference(t) , s - t
Symmetric Difference: s.symmetric_difference(t) , s ˆ t
Copy: s.copy()
As with sequences, the following works:
x in s , len(s) , for x in s , s.add(x) , s.remove(x)
Slide 67
Dictionaries
Other names: Hash, Map, Associative Array
Mapping of key → value
Keys are unordered
>>> s t or e = { " s pam" : 1, " eggs " : 17}
>>> s t or e [ " eggs " ]
17
>>> s t or e [ " bac on" ] = 42
>>> st o re
{ ’ eggs ’ : 17, ’ bac on’ : 42, ’ s pam’ : 1}
Iterating over dictionaries:
f or key i n s t or e :
pr i nt ( key , s t or e [ key ] )
Compare two dictionaries: store == pool
Not allowed: > , >= , < , <=
Slide 68
Operations on Dictionaries
Delete an entry: del(store[key])
Delete all entries: store.clear()
Copy: store.copy()
Does it contain a key? key in store
Get an entry: store.get(key[, default])
Remove and return entry: store.pop(key[, default])
Remove and return arbitrary entry: store.popitem()
Slide 69
Operations on Dictionaries
Delete an entry: del(store[key])
Delete all entries: store.clear()
Copy: store.copy()
Does it contain a key? key in store
Get an entry: store.get(key[, default])
Remove and return entry: store.pop(key[, default])
Remove and return arbitrary entry: store.popitem()
Views on Dictionaries
Create a view: items() , keys() and values()
List of all (key, value) tuples: store.items()
store.keys()
List of all keys:
List all values: store.values()
Caution: Dynamical since Python 3
Slide 69
3/4/2023
Views Behavior: Python 2.X versus Python 3.X
Python 2 (static)
>>> m
di c t ={ " a" : 2, " d" : 5}
>>> mdict
{ ’ a’ : 2, ’ d’ : 5}
>>> s =m
di c t . i t em
s ( )
>>> fo r i in s :
pr i nt ( i )
( ’ a ’ , 2)
( ’ d ’ , 5)
>>> m
di c t [ ’ a’ ] =- 1
>>> mdict
{ ’ a’ : - 1, ’ d’ : 5}
>>> fo r i in s :
pr i nt ( i )
( ’ a ’ , 2)
( ’ d ’ , 5)
Python 3 (dynamic)
>>> m
di c t ={ " a" : 2, " d" : 5}
>>> mdict
{ ’ a’ : 2, ’ d’ : 5}
>>> s =m
di c t . i t em
s ( )
>>> fo r i in s :
pr i nt ( i )
( ’ a ’ , 2)
( ’ d ’ , 5)
>>> m
di c t [ ’ a’ ] =- 1
>>> mdict
{ ’ a’ : - 1, ’ d’ : 5}
>>> fo r i in s :
pr i nt ( i )
( ’ a ’ , -1)
( ’ d ’ , 5)
Slide 70
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Slide 71
Object Oriented Programming (OOP)
So far: procedural programming
Data (values, variables, parameters, . ..)
Functions taking data as parameters and returning results
Alternative: Group data and functions belonging together to form custom data types
→ Extensions of structures in C/Fortran
Slide 72
Using Simple Classes as Structs
my_point.py
c l a s s P o i n t :
pass
p = Poi nt ( )
p. x = 2. 0
p. y = 3. 3
Class: Custom date type (here: Point )
Object: Instance of a class (here: p )
Attributes (here x , y ) can be added dynamically
pass
Hint: is a No Operation (NOOP) function
Slide 73
3/4/2023
Classes - Constructor
my_point.py
c l a s s P o i n t :
def _ _ i ni t _ _ ( sel f , x , y) :
s el f . x = x
s el f . y = y
p = Poi nt ( 2. 0, 3. 0)
pr i nt ( p. x , p. y)
p. x = 2. 5
p. z = 42
init : Is called automatically after creating an object
Slide 74
Methods on Objects
my_point.py
import math
c l a s s P o i n t :
def _ _ i ni t _ _ ( sel f , x , y) :
s el f . x = x
s el f . y = y
def nor m
( s el f ) :
n= math. s q r t ( s e l f . x**2 + s e l f . y**2)
return n
p = Poi nt ( 2. 0, 3. 0)
pr i nt ( p. x , p. y, p. nor m( ) )
Method call: automatically sets the object as first parameter
→ traditionally called self
Careful: Overloading of methods not possible!
Slide 75
Converting Objects to Strings
Default return value of s t r ( . . . ) for objects of custom classes:
>>> p = Poi nt ( 2. 0, 3. 0)
>>> pr i nt ( p) # --> print(str(p))
<_ _ m a i n _ _ . Point in stan c e at 0x402d7a8c >
Slide 76
Converting Objects to Strings
Default return value of s t r ( . . . ) for objects of custom classes:
>>> p = Poi nt ( 2. 0, 3. 0)
>>> pr i nt ( p) # --> print(str(p))
<_ _ m a i n _ _ . Point in stan c e at 0x402d7a8c >
This behaviour can be overwritten:
my_point.py
c l a s s P o i n t :
[ . . . ]
def _ _ s t r _ _ ( s el f ) :
return " ( { 0 } , { 1 } ) " . format( s e l f . x , s e l f . y)
>>> pr i nt ( p)
( 2. 0, 3. 0)
Slide 76
3/4/2023
Comparing Objects
==
Default: checks for object identity of custom objects.
>>> p1 = Poi nt ( 2. 0, 3. 0)
>>> p2 = Poi nt ( 2. 0, 3. 0)
>>> p1 == p2
F al se
Slide 77
Comparing Objects
==
Default: checks for object identity of custom objects.
>>> p1 = Poi nt ( 2. 0, 3. 0)
>>> p2 = Poi nt ( 2. 0, 3. 0)
>>> p1 == p2
F al se
This behaviour can be overwritten:
c l a s s P o i n t :
[ . . . ]
def _ _ eq_ _ ( s el f , ot her ) :
r et ur n ( s el f . x == ot her . x) and ( s el f . y == ot her . y)
my_point.py
equal values
identity
>>> p1 == p2 # Check for
True
>>> p1 i s p2 # Check for
F al se
Slide 77
Operator overloading
More relational operators:
< : l t ( s e l f, other)
<= le ( s e l f, other)
:
!= : ne ( s e l f , other)
> : gt ( s e l f , other)
>= : ge ( s e l f , other)
Numeric operators:
add ( s e l f , other)
sub ( s e l f , other)
+ :
- :
* :
...
mul ( s e l f , other)
Emulating Existing Data Types
Classes can emulate built-in data types:
Numbers: arithmetics, int(myobj) , float(myobj) , .. .
Functions: myobj(...)
Sequences: len(myobj) , myobj[...] , x in myobj , ...
Iteratores: for i in myobj
See documentation: http://docs.python.org/3/reference/datamodel.html
3/4/2023
Class Variables
Have the same value for all instances of a class:
c l a s s P o i n t :
count = 0 # Count all point objects
my_point.py
def _ _ i ni t _ _ ( sel f , x , y) :
Poi nt . c ount += 1 #self.__class__.count += 1
[ . . . ]
>>> p1 = Poi nt ( 2, 3) ; p2 = Poi nt ( 3, 4)
>>> p1. c ount
2
>>> p2. c ount
2
>>> Poi nt . c ount
2
Class Methods and Static Methods
c l as s Spam
:
s pam = " I don’ t l i ke s pam
. "
@
c l as s m
et hod
def c m
et hod( c l s ) :
pr i nt ( c l s . s pam)
@
s t at i c m
et hod
def s m
et hod( ) :
pr i nt ( " Bl ah bl ah. " )
spam.py
Spam
. c m
et hod( )
Spam
. s m
et hod( )
s = Spam( )
s . c m
et hod( )
s . s m
et hod( )
Inheritance (1)
There are often classes that are very similar to each other.
Inheritance allows for:
Hierarchical class structure (is-a-relationship)
Reusing of similar code
Example: Different types of phones
Phone
Mobile phone (is a phone with additional functionality)
Smart phone (is a mobile phone with additional functionality)
Inheritance (2)
c l as s Phone:
def c al l ( s el f ) :
pass
c l as s M
obi l ePhone( Phone) :
def s end_ t ext ( s el f ) :
pass
MobilePhone now inherits methods and attributes from Phone.
h = M
obi l ePhone ( )
h. c al l ( ) # inherited from Phone
h. s end_ t ext ( ) # own method
3/4/2023
Overwriting Methods
Methods of the parent class can be overwritten in the child class:
c l as s M
obi l ePhone( Phone) :
def c al l ( s el f ) :
s el f . f i nd_ s i gnal ( )
Phone. c al l ( s el f )
Multiple Inheritance
Classes can inherit from multiple parent classes. Example:
SmartPhone is a mobile phone
SmartPhone is a camera
c l a s s SmartPhone ( MobilePhone , Camera ) :
pass
h = Sm
ar t Phone ( )
h. c al l ( ) # inherited from MobilePhone
h. t ake_ phot o( ) # inherited from Camera
Attributes are searched for in the following order:
MobilePhone
SmartPhone , MobilePhone , parent class of (recursively), Camera ,
parent class of Camera (recursively).
Private Attributes / Private Class Variables
There are no private variables or private methods in Python.
Convention: Mark attributes that shouldn’t be accessed from outside with an
underscore: _foo .
foo
To avoid name conflicts during inheritance: Names of the form are replaced
with _classname foo :
c l as s Spam
:
_ _ egg s = 3
_bacon = 1
beans = 5
>>> di r ( Spam
)
>>> [ ’ _Spam__eggs ’ , ’ _ _ d o c _ _ ’ , ’ __module__ ’ , ’ _bacon ’ , ’ beans ’ ]
Classic (old Style) Classes
The only class type until Python 2.1
In Python 2 default class
New Style Classes
Unified class model (user-defined and build-in)
Descriptores (getter, setter)
The only class type in Python 3
Available as basic class in Python 2: object
3/4/2023
Properties (1)
If certain actions (checks, conversions) are to be executed while accessing attributes, use
getter and setter:
c l as s Spam
:
def _ _ i ni t _ _ ( s el f ) :
s el f . _ val ue = 0
def get _ val ue( s el f ) :
r et ur n s el f . _ val ue
def s et _ val ue( sel f , val ue ) :
i f value <= 0:
s el f . _ val ue = 0
el s e :
s el f . _ val ue = val ue
val ue = pr oper t y( get _ val ue , s et _ val ue)
Properties (2)
Properties can be accessed like any other attributes:
>>> s = Spam( )
# set_value(6)
# get_value()
# set_value(-6)
# get_value()
>>> s . val ue = 6
>>> s . val ue
6
>>> s . val ue = - 6
>>> s . val ue
0
Getter and setter can be added later without changing the API
_value
Access to still possible
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Importing Modules
Reminder: Functions, classes and object thematically belonging together are grouped in
modules.
import math
s = m
at h. s i n( m
at h. pi )
import math as m
s = m
. s i n( m
. pi )
f r om m
at h i m
por t pi as PI , s i n
s = si n ( P I )
from math import *
s = s i n( pi )
Online help: dir(math) , help(math)
3/4/2023
Creating a Module (1)
Every Python script can be imported as a module.
my_module.py
"""My first module: my_module.py"""
def add( a, b) :
"""Add a and b."""
return a + b
pr i nt ( add( 2, 3) )
>>> import my_module
5
>>> m
y_ m
odul e. add( 17, 42)
59
Top level instructions are executed during import!
Creating a Module (2)
If instructions should only be executed when running as a script, not importing it:
my_module.py
def add( a, b) :
return a + b
def m
ai n( ) :
pr i nt ( add( 2, 3) )
i f _ _ nam
e_ _ == " _ _ m
ai n_ _ " :
m
ai n( )
Useful e.g. for testing parts of the module.
Creating a Package
Modules can be grouped into hierarchically structured packages.
numeric
init .py
linalg
init .py
decomp.py
eig.py
solve.py
fft
init .py
...
Packages are subdirectories
In each package directory:
init .py (may be empty)
import numeric
num
er i c . f oo( ) # from __init__.py
num
er i c . l i nal g . ei g . f oo( )
f r om num
er i c . l i nal g i m
por t ei g
ei g. f oo( )
Modules Search Path
Modules are searched for in (see sys.path ):
The directory of the running script
Directories in the environment variable PYTHONPATH
Installation-dependent directories
>>> import sys
>>> s ys . pat h
[ ’ ’ , ’ /us r / l i b/ pyt hon37. z i p’ ,
’ /us r / l i b64/ pyt hon3. 7’ ,
’ / usr/ l ib 64 / python3.7 / p lat - l i n u x ’ , . . . ]
3/4/2023
Python’s Standard Library
„Batteries included“: comprehensive standard library for various tasks
Mathematics: math
Constants: e , pi
Round up/down: floor(x) , ceil(x)
Exponential function: exp(x)
Logarithm: log(x[, base]) , log10(x)
Power and square root: pow(x, y) , sqrt(x)
Trigonometric functions: sin(x) , cos(x) , tan(x)
radians(x)
Conversion degree ↔radiant: degrees(x) ,
>>> import math
>>> m
at h. s i n( m
at h. pi )
1. 2246063538223773e - 16
>>> m
at h. c os ( m
at h. r adi ans ( 30) )
0. 86602540378443871
Random Numbers: random
Random integers:
randint(a, b) , randrange([start,] stop[, step])
Random floats (uniform distr.): random() , uniform(a, b)
Other distibutions: expovariate(lambd) , gammavariate(alpha, beta) ,
gauss(mu, sigma) , .. .
Random element of a sequence: choice(seq)
Several unique, random elements of a sequence: sample(population, k)
shuffle(seq[, random])
Shuffled sequence:
>>> import random
wor l d! " )
>>> s = [ 1, 2, 3, 4, 5]
>>> r andom
. s huf f l e( s )
>>> s
[ 2, 5, 4, 3, 1]
>>> r andom
. c hoi c e( " Hel l o
’ e ’
Time Access and Conversion: time
Classical time() functionality
int
Time class type is a 9-tuple of values ( struct_time )
Time starts at epoch (for UNIX: 1.1.1970, 00:00:00)
Popular functions:
Seconds since epoch (as a float):
Convert time in seconds (float) to
time.time()
struct_time : time.localtime([seconds])
If seconds is None the actual time is returned.
Convert
Convert
struct_time in seconds (float): time.mktime(t)
struct_time in formatted string: time.strftime(format[, t ] )
Suspend execution of current thread for secs seconds: time.sleep(secs)
3/4/2023
Date and Time: datetime
Date and time objects:
d1 = dat et i m
e. dat e ( 2008, 3, 21)
d2 = dat et i m
e. dat e ( 2008, 6, 22)
dt = dat et i m
e. dat et i m
e ( 2011, 8, 26, 12, 30)
t = dat et i m
e. t i m
e ( 12, 30)
Calculating with date and time:
pr i nt ( d1 < d2)
d e l t a = d2 - d1
pr i nt ( del t a . days )
pr i nt ( d2 + dat et i m
e. t i m
edel t a( days =44) )
Operations on Path Names: os.path
Paths: abspath(path) , basename(path) , normpath(path) , realpath(path)
Construct paths: join(path1[, path2[, . . . ] ] )
Split paths: split(path) , splitext(path)
File information: isfile(path) , isdir(path) , islink(path) , getsize(path) ,
.. .
Expand home directory: expanduser(path)
Expand environment variables: expandvars(path)
>>> os . pat h. j oi n( " s pam" , " eggs " , " ham. t xt " )
’ spam/ eggs/ ham. t x t ’
>>> o s . path . s p l i t e x t ( " spam/ e g g s . py")
( ’ s pam/ eggs ’ , ’ . py’ )
>>> os . pat h. expandus er ( " ~/ s pam" )
’ /hom
e/ r br eu/ s pam’
>>> os . pat h. expandvar s ( " /m
ydi r / $TEST" )
’ / mydir/ t e s t . py’
Files and Directories: os
Working directory: getcwd() , chdir(path)
Changing file permissions: chmod(path, mode)
Changing owner: chown(path, uid, gid)
Creating directories: mkdir(path[, mode]) , makedirs(path[, mode])
Removing files: remove(path) , removedirs(path)
Renaming files: rename(src, dst) , renames(old, new)
List of files in a directory: listdir(path)
f or m
yf i l e i n os . l i s t di r ( " m
ydi r " ) :
os . c hm
od( os . pat h. j oi n( " m
ydi r " , m
yf i l e) ,
os . pat h. s t at . S_ I RGRP)
Files and Directories: shutil
Higher level operations on files and directories. Mighty wrapper functions for os module.
Copying files: copyfile(src, dst) , copy(src, dst)
Recursive copy: copytree(src, dst[, symlinks])
Recursive removal:
rmtree(path[, ignore_errors[, onerror]])
Recursive move: move(src, dst)
s hut i l . c opyt r ee( " s pam/ eggs " , " . . / beans " ,
s ym
l i nks =Tr ue)
3/4/2023
Directory Listing: glob
glob(path)
List of files in a directory with Unix-like extension of wildcards:
>>> gl ob. gl ob( " pyt hon/[ a- c ] * . py" )
[ ’ pyt hon/ c onf i t es t . py’ ,
’ pyt hon/ bas i c s . py’ ,
’ pyt hon/ c ur s es _ t es t 2. py’ ,
’ pyt hon/ c ur s es _ keys . py’ ,
’ pyt hon/c m
p. py’ ,
’ pyt hon/ but t on_ t es t . py’ ,
’ pyt hon/ ar gum
ent . py’ ,
’ pyt hon/ c ur s es _ t es t . py’ ]
Run Processes: subprocess
Simple execution of a program:
p = s ubpr oc es s . Popen( [ " l s " , " - l " , " m
ydi r " ] )
r et ur nc ode = p. wai t ( ) # wait for p to end
Access to the program’s output:
p = Popen ( [ " l s " ] , stdout=PIPE , std err= STDOUT)
p . wait ( )
out put = p. s t dout . r ead( )
Pipes between processes ( l s - l | grep txt )
p1 = Popen ( [ " l s " , " - l " ] , stdout= PIPE )
p2 = Popen ( [ " grep " , " t x t " ] , std in =p1. s tdo ut)
Access to Command Line Parameters: argparse (1)
Python program with standard command line option handling:
$ . / ar gum
ent Par s er . py - h
us age : ar gum
ent Par s e . py [ - h] - f FI LENAM
E [ - v]
Example how to use argparse
o pti o n al arguments:
- h, - - hel p
- f FI LENAM
E, - - f i l e FI LENAM
E
- v, - - ver bos i t y
show t h i s help message and e x i t
output f i l e
i nc rease output verb o si ty
$ pyt hon3 ar gum
ent Par s e. py - f newf i l e. t xt - v
new fi l e . t x t
True
Access to Command Line Parameters: argparse (2)
Simple list of parameters: → sys.argv
More convenient for handling several options: argparse
optparse
Deprecated module (since Python 2.7/3.2)
argumentParse.py
par s er = ar gpar s e. Ar gum
ent Par s er (
d e s c r i p t i o n = ’ Example howto use argparse ’ )
p a r s e r . a d d _ a r g u me nt (" -f " , " - - f i l e " ,
des t =" f i l enam
e" ,
def aul t =" out . t xt " ,
hel p=" out put f i l e " )
p a r s e r . a d d _ a r g u m e n t ( " - v ", " - - verb o si ty " ,
ac t i on=" s t or e_ t r ue" ,
hel p=" i nc r eas e out put ver bos i t y" )
ar gs = par s er . par s e_ ar gs ( )
pr i nt ( ar gs . f i l enam
e)
pr i nt ( ar gs . ver bos i t y)
3/4/2023
CSV Files: csv (1)
CSV: Comma Seperated Values
Data tables in ASCII format
Import/Export by MS Excel Ⓧ
R
Columns are delimited by a predefined character (most often comma)
f = open( " t es t . c s v" , "
r " ) r eader = c s v. r eader (
f ) fo r row in r e a d e r :
f or i t em i n r ow:
pr i nt ( i t em)
f . c l os e ( )
f = open( out f i l e , "
w" ) wr i t er = c s v.
wr i t er ( f )
wr i t er . wr i t er ow( [ 1, 2, 3, 4] )
CSV Files: csv (2)
Handling different kinds of formats (dialects):
csv . reader( c s v f i l e , d i a l e c t = ’ exc el ’ ) # Default
c s v. wr i t er ( c s vf i l e , di al ec t =’ exc el _ t ab’ )
Specifying individual format parameters:
c s v. r eader ( c s vf i l e , del i m
i t er =" ; " )
Further format parameters: lineterminator , quotechar , skipinitialspace , .. .
sqlite3
Lightweight Database: (1)
Database in a file or in memory; in Python’s stdlib since 2.5.
c onn = s ql i t e3. c onnec t ( " bl a . db" )
c = c onn. c ur s or ( )
TEXT)""")
c . exec ut e( """CREATE TABLE Friends
(firstname TEXT, lastname
c . exec ut e( """INSERT INTO Friends
VALUES("Jane", "Doe")""")
c onn. c om
m
i t ( )
c . exec ut e( """SELECT * FROM Friends""")
fo r row in c :
pr i nt ( r ow)
c . c l os e ( ) ;
c onn. c l os e ( )
sqlite3
Lightweight Database: (2)
String formatting is insecure since it allows injection of arbitrary SQL code!
# Never do this!
s ym
bol = " J ane"
c . execute ( " . . . WHERE fi rs tnam e =’ { 0 } ’ " . format( symbol ) )
3/4/2023
sqlite3
Lightweight Database: (3)
Instead: Use the placeholder the database API provides:
c . exec ut e( " . . . W
HERE nam
e = ? " , s ym
bol )
f r i e n d s = ( ( " J a n i s " , " J o p l i n " ) , ( " Bob" , " Dylan " ) )
fo r item in f r i e n d s :
c . exec ut e( """INSERT INTO Friends
VALUES (?,?)""", i t em)
cx_Oracle
⇒ Python module to access Oracle database
Web page: http://cx-oracle.sourceforge.net/
XML based Client-Server Communication: xmlrpc (1)
XML-RPC: Remote Procedure Call uses XML via HTTP
Independent of platform and programming language
For the client use xmlrpc.client
i m
por t xm
l r pc . c l i ent
s = xml rp c . c l i e n t . S e r v e r ( " h ttp :// l o c a l h o s t :8000 " )
# print list of available methods
pr i nt ( s . s ys t em
. l i s t M
et hods ( ) )
# use methods
pr i nt ( s . add( 2, 3) )
pr i nt ( s . s ub( 5, 2) )
Automatic type conversion for the standard data types: boolean, integer, floats, strings,
tuple, list, dictionarys (strings as keys), . ..
XML based Client-Server Communication: xmlrpc (2)
For the server use xmlrpc.server
from xml rp c . s erver import Simple XMLRPCServer
offered by the server:
# methods which are to be
c l as s M
yFunc s :
def add( s el f , x , y) :
return x + y
def s ub( s el f , x , y) :
return x - y
# create and start the server:
server = Simple XMLRPCServer ( ( " l o c a l h o s t " , 8000))
s e r v e r . r e g i s t e r _ i n s t a n c e ( My Funcs ( ) )
s e r v e r . s e r v e _ f o r e v e r ( )
More Modules
readline : Functionality for command line history and auto-completion
tempfile : Generate temporary files and directories
numpy: Numeric Python package
N-dimensional arrays
Supports linear algebra, Fourier transform and random number capabilities
Part of the SciPy stack
mathplotlib : 2D plotting library, part of the SciPy stack
...
3/4/2023
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Conditional Expressions
A conditional assignment as
i f value <0:
s = " negat i ve"
el s e :
s = " pos i t i ve"
can be realized in abbreviated form
s = " negat i ve" i f val ue <0 el s e " pos i t i ve"
List Comprehension
Allows sequences to be build by sequences. Instead of using for :
a = [ ]
f or i i n r ange ( 10) :
a. append( i * * 2)
List comprehension can be used:
a = [ i * * 2 f or i i n r ange ( 10) ]
Conditional values in list comprehension:
a = [ i * * 2 f or i i n r ange ( 10) i f i ! = 4]
Since Python 2.7: set and dictionary comprehension
s = { i * 2 f or i i n r ange ( 3) }
d = { i : i * 2 f or i i n r ange ( 3) }
Dynamic Attributes
Remember: Attributes can be added to python objects at runtime:
c l as s Em
pt y:
pass
a = Em
pt y( )
a. s pam = 42
a. eggs = 17
Also the attributes can be deleted at runtime:
del ( a. s pam)
3/4/2023
getattr , setattr , hasattr
Attributes of an object can be accessed by name (string):
import math
f = get at t r ( m
at h, " s i n
" ) pr i nt ( f ( x) ) # sin(x)
a = Em
pt y( )
s et at t r ( a, " s pam" , 42)
pr i nt ( a. s pam)
Useful if depending on user or data input.
Check if attribute is defined:
i f not has at t r ( a, " s pam" ) :
s et at t r ( a, " s pam" , 42)
pr i nt ( a. s pam)
Anonymous Function Lambda
Also known as lambda expression and lambda form
>>> f = lambda x , y : x + y
>>> f ( 2, 3)
5
>>> ( l am
bda x: x * * 2) ( 3)
9
Useful if only a simple function is required as an parameter in a function call:
>>> f r i ends = [ " al i c e " , " Bob" ]
>>> f r i ends . s or t ( )
>>> f r i e n d s
[ ’ Bob’ , ’ al i c e ’ ]
>>> f r i ends . s or t ( key = l am
bda a: a. upper ( ) )
>>> f r i e n d s
[ ’ al i c e ’ , ’ Bob’ ]
Functions Parameters from Lists and Dictionaries
def s pam( a, b, c , d) :
p r i n t ( a , b , c , d)
Positional parameters can be created by lists:
>>> ar gs = [ 3, 6, 2, 3]
>>> s pam( * ar gs )
3 6 2 3
Keyword parameters can be created by dictionaries:
>>> kwar gs = { " c " : 5, " a" : 2, " b" : 4, " d" : 1}
>>> s pam( * * kwar gs )
2 4 5 1
Variable Number of Parameters in Functions
def s pam( * ar gs , * * kwar gs ) :
fo r i in a r g s :
pr i nt ( i )
fo r i in kwargs:
pr i nt ( i , kwar gs [ i ] )
>>> s pam( 1, 2, c =3, d=4)
1
2
c. 3
d. 4
3/4/2023
Global and Static Variables in Functions
global links the given name to a global variabile
Static variable can be defined as an attribute of the function
def m
yf unc ( ) :
g l o b al max_size
i f not has at t r ( m
yf unc , " _ c ount er " ) :
m
yf unc . _ c ount er = 0 # it doesn’t exist yet,
# so initialize it
m
yf unc . _ c ount er += 1
pr i nt ( " { 0: d} . c al l " . f or m
at ( m
yf unc . _ c ount er ) )
pr i nt ( " m
ax s i z e i s { 0: d} " . f or m
at ( m
ax_ s i z e ) )
. . .
>>> max_size = 222
>>> m
yf unc ( )
1 . c a l l
max s i z e i s 222
Map
Apply specific function on each list element:
>>> l i = [ 1, 4, 81, 9]
>>> m
apl i = m
ap( m
at h. sqr t , l i )
>>> mapli
<m
ap obj ec t at 0x7f 5748240b90 >
>>> l i s t ( m
apl i )
[ 1. 0, 2. 0, 9. 0, 3. 0]
>>> l i s t ( m
ap( l am
bda x: x * 2, l i ) )
[2 , 8, 162, 18]
Functions with more than one parameter requires an additional list per parameter:
>>> l i s t ( m
ap( m
at h. pow, l i , [ 1, 2, 3, 4] ) )
[ 1. 0, 16. 0, 531441. 0, 6561. 0]
Filter
Similar to map, but the result is a f i l t e r object, which contains only list elements,
where the function returns True .
filter_example.py
l i = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
l i Odd = f i l t er ( l am
bda x: x % 2, l i )
p r i n t ( " l i = " , l i )
pr i nt ( " l i Odd =" , l i Odd)
p r i n t ( " l i s t ( liOdd ) = " , l i s t ( liOdd ) )
$ pyt hon3 f i l t er _ exam
pl e. py
l i = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
liOdd = < f i l t e r o b j e c t at 0x7fe4 ccdcb 7c0 >
l i s t ( l i Odd) = [ 1, 3, 5, 7, 9]
$
Zip
Join multiple sequences to one list of tuples:
Useful when iterating on multiple sequences in parallel
>>> l i s t ( z i p( " ABC" , " 123" ) )
[ ( ’ A’ , ’ 1’ ) , ( ’ B’ , ’ 2’ ) , ( ’ C’ , ’ 3’ ) ]
>>> l i s t ( z i p( [ 1, 2, 3] , " ABC" , " XYZ" ) )
[ ( 1, ’ A’ , ’ X’ ) , ( 2, ’ B’ , ’ Y’ ) , ( 3, ’ C’ , ’ Z’ ) ]
Example: How to create a dictionary by two sequences
>>> di c t ( z i p( ( " appl e" , " peac h" ) , ( 2, 0) ) )
{ ’ appl e ’ : 2, ’ peac h’ : 0}
3/4/2023
Iterators (1)
for is applied on an object?
What happens, if
fo r i in o b j :
pass
iter
The method for obj is called, return an iterator.
On each loop cycle the iterator. next () method will be called.
StopIteration
The exception is raised when there are no more elements.
Advantage: Memory efficient (access time)
Iterators (2)
c l as s Rever s e:
def _ _ i ni t _ _ ( sel f , dat a ) :
s el f . dat a = dat a
s el f . i ndex = l en( dat a )
def _ _ i t er _ _ ( s el f ) :
return s e l f
def _ _ next _ _ ( s el f ) :
i f s el f . i ndex == 0:
s el f . i ndex = l en( s el f . dat a )
r ai s e St opI t er at i on
s el f . i ndex = s el f . i ndex - 1
r et ur n s el f . dat a [ s el f . i ndex ]
>>> f or c har i n Rever s e( " s pam" ) :
pr i nt ( c har , end=" " )
. . .
. . .
m a p s
Generators
Simple way to create iterators:
yield
Methods uses the statement
⇒ breaks at this point, returns element and continues there on the next
iterator. next () call.
def r ever s e( dat a ) :
f or el em
ent i n dat a [ : : - 1] :
y i e l d element
>>> f or c har i n r ever s e( " s pam" ) :
pr i nt ( c har , end=" " )
. . .
. . .
m a p s
Generator Expressions
Similar to the list comprehension an iterator can be created using a generator expression:
>>> dat a = " s pam"
>>> f or c i n ( el em f or el em i n dat a [ : : - 1] ) :
pr i nt ( c , end=" " )
. . .
. . .
m a p s
3/4/2023
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
IPython (I)
Enhanced interactive Python shell
Numbered input/output prompts
Object introspection
System shell access
IPython (II)
Tab-completion
Command history retrieval across session
User-extensible ‘magic’ commands
%timeit ⇒Time execution of a Python statement or expression using the timeit module
%cd ⇒Change the current working directory
%edit ⇒Bring up an editor and execute the resulting code
%run ⇒Run the named file inside IPython as a program
⇒more ’magic’ commands
⇒IPython documentation
PIP Installs Python/Packages (I)
Command pip
A tool for installing Python packages
Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include
by default
Installing Packages
pip
$ pi p3 i ns t al l Som
ePac kage
$ pi p3 i ns t al l - - us er Som
ePac kage #us er i ns t al l
Uninstall Packages
$ pi p3 uni ns t al l Som
ePac kage
3/4/2023
PIP Installs Python/Packages (II)
Listing Packages
$ pip3 l i s t
doc ut i l s ( 0. 9. 1)
J i nj a2 ( 2. 10)
Pygm
ent s ( 2. 3. 1)
Sphi nx ( 1. 1. 2)
$ pi p3 l i s t - - out dat ed
doc ut i l s ( Cur r ent : 0. 9. 1 L a t e s t : 0. 14)
Sphi nx ( Cur r ent : 1. 1. 2 Lat es t : 2. 10)
Searching for Packages
$ pi p3 s ear c h " quer y"
⇒pip documentation
pyenv - Simple Python Version Management (I)
Easily switch between multiple versions of Python
Doesn’t depend on Python itself
Inserts directory of shims4 at the front of your
Easy Installation:
PATH
$ g i t clone http s :// github . com/ yyuu / pyenv. g i t ~/. pyenv
$ ec ho ’ expor t PYENV_ ROOT=" $ HOM
E/. pyenv" ’ >> ~/. bas hr c
$ echo ’ export PATH=" $ PYENV_ROOT/bin : $ PATH" ’ >> ~/. bashrc
$ ec ho ’ eval " $ ( pyenv i ni t - ) " ’ >> ~/. bas hr c
⇒pyenv repository
4
kind of infrastructure to redirect system/function calls
metaphor: A shim is a piece of wood or metal to make two things fit together
pyenv - Simple Python Version Management (II)
Install Python versions into $PYENV_ROOT/versions
$ pyenv i ns t al l - - l i s t
$ pyenv i n s t a l l 3 . 7 . 4
# a v a i l a b l e Python vers io ns
#i n s t a l l Python 3 . 7 . 4
Change the Python version
$ pyenv g l o b a l 3 . 7 . 4
$ pyenv l o c a l 3 . 7 . 4
$ pyenv s h e l l 3 . 7 . 4
# g l o b a l Python
# per - pr oj ec t Pyt hon
# s hel l - s pec i f i c Pyt hon
List all installed Python versions (asterisk shows the active)
$ pyenv versi o n s
system
2. 7. 16
* 3 . 7 . 4 ( set by PYENV_VERSION environment v a r i a b l e )
Virtual Environments
Allow Python packages to be installed in an isolated location
Use cases
Two applications need different versions of a library
Install an application and leave it be
Can’t install packages into the global site-packages directory
Virtual environments have their own installation directories
Virtual environments don’t share libraries with other virtual environments
Available implementations:
virtualenv (Python 2 and Python 3)
venv (Python 3.3 and later)
3/4/2023
venv
Create virtual environment
$ pyt hon3 - m venv / pat h/t o/env
Activate
$ s our c e / pat h/t o/env/bi n/ ac t i vat e
Deactivate
$ d e a c t i v a t e
⇒venv documentation
Pylint (I)
pylint li n t
is the implementation for python code
Checks for errors in Python code
Tries to enforce a coding standard
Looks for bad code smells
Displays classified messages under various categories such as errors and warnings
Displays statistics about the number of warnings and errors found in different files
Pylint (II)
The code is given an overall mark
$ pyt hon3 - m pyl i nt exam
pl e. py
. . .
G l o bal evaluat io n
- - - - - - - - - - - - - - - - -
Your c ode has been r at ed at 10. 00/10
( pr evi ous r un: 9. 47/10, +0. 53)
⇒Pylint documentation
Software testing
Part of quality management
Point out the defects and errors that were made during the development phases
It always ensures the users or customers satisfaction and reliability of the application The
cost of fixing the bug is larger if testing is not done ⇒testing saves time
Python testing tools
pytest
unittest
. ..
3/4/2023
pytest
Easy to get started
test_ prefixed test functions or methods are test items
assert
Asserting with the statement
pytest will run all files in the current directory and its subdirectories of the form
test_*.py or *_test.py
Usage:
$ pyt hon3 - m pyt es t
. . .
$ pyt hon3 - m pyt es t exam
pl e . py
. . .
⇒pytest documentation
pytest Example: Check Function Return Value
example1_test.py
def i nc r ( x ) :
return x + 11
def t es t _ i nc r ( ) :
as s er t i nc r ( 3) == 4
$ python3 -m p yt est -v example1_ t e s t . py
. . .
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ t e s t _ i n c r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
E
E
def t es t _ i nc r ( ) :
as s er t i nc r ( 3) == 4
a s s e r t 14 == 4
+ wher e 14 = i nc r ( 3)
exam
pl e1_ t es t . py : 5: As s er t i onEr r or
============= 1 f a i l e d in 0.00 seconds =============
pytest Example: Check for expected Exception
import pytest
def f ( ) :
r ai s e Sys t em
Exi t ( 1)
def t es t _ er r or ( ) :
wi t h pyt es t . r ai s es ( Sys t em
Exi t ) : #passes
f ( )
Slide 146
pytest Example: Check for expected Exception
import pytes t
def f ( ) :
r ai s e Sys t em
Exi t ( 1)
def t es t _ er r or ( ) :
wi t h pyt es t . r ai s es ( Sys t em
Exi t ) : #passes
f ( )
pytest Example: Comparing Two Data Object
def t e s t _ l i s t _ c o m p a r i s o n ( ) :
l i s t 1 = [ 1, 3, 0, 8]
l i s t 2 = [ 1, 3, 3, 8]
a s s e r t l i s t 1 == l i s t 2 #fails
Slide 146
3/4/2023
pytest Example: Parameterize Test Function
def i nc r ( x ) :
return x + 1
@
p y t e s t . mark. parametrize ( " t e s t _ i n p u t , expected " , [
(1 , 2 ) ,
( 2, 3) ,
( 3, 4) ,
] )
def t es t _ i nc r ( t es t _ i nput , expec t ed) :
a s s e r t i n c r ( t e s t _ i n p u t ) == expected
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Techniques
Tools
Regular Expressions (optional)
Summary and Outlook
Regular Expressions – Introduction
Regular expression (RegExp):
Formal language for pattern matching in strings
Motivation: Analyze various text files:
Log files
Data files (e.g. experimental data, system configuration, . . .)
Command output
. ..
Python module: import re
>>> r e. f i ndal l ( r " a. c " , " abc aac aa abb a c " )
[ ’ a b c ’ , ’ aac ’ , ’ a c ’ ]
Remember:
r " . . . " ⇒ raw string (escape sequences are not interpreted)
Regular Expressions – Character Classes
Class/set of possible characters: [ ! ? : . , ; a - z ]
ˆ at the beginning negates the class.
e.g.: [ˆaeiou] ⇒ all characters besides the vocals
Character class in pattern tests for one character
The . represents any (one) character
Predefined character classes:
name
whitespace
word character
d i g i t
character
[  t  n  r  f ]
Acr . negated
 s S
w W
 d D
[ a−zA−Z_0−9]
[0−9]
>>> r e. f i ndal l ( r " s ds " , " 1 22 4 22 1 a b c " )
[ ’ 4 ’ , ’ 1 ’ ]
>>> r e. f i ndal l ( r " [ ^aei ou] " , " Pyt hon Kur s " )
[ ’ P ’ , ’ y ’ , ’ t ’ , ’ h ’ , ’ n ’ , ’ ’ , ’ K ’ , ’ r ’ , ’ s ’ ]
3/4/2023
Regular Expressions – Quantifiers
Quantifier can be defined in ranges (min, max):
d{5,7} matches sequences of 5-7 digits
Acronym:
{1}
{0 ,}
{0 ,1}
{1 ,}
one−time occurrence Default
none to multiple occurrences ∗
none or one−time occurrence ?
+
at least one−time occurrence
>>> r e . f i n d a l l ( r " [ ab ] {1 , 2 } " , " a aa ab ba bb b ")
[ ’ a’ , ’ aa ’ , ’ ab’ , ’ ba ’ , ’ bb’ , ’ b’ ]
>>> r e . f i n d a l l ( r" d + " , " 1 . Python Kurs 2012" )
[ ’ 1’ , ’ 2012’ ]
Regular Expressions – Anchors
Anchors define special restrictions to the pattern matching:
 b
B
^
$
word boundary , switch between w and W
negate  b
s t ar t of the s t ri ng
end of the s t r i ng
>>> r e . f i n d a l l ( r " ^d + " , " 1 . Python Course 2015" )
[ ’ 1’ ]
Look-around anchors (context):
Lookahead
ab(?=c )
ab ( ?! c )
Lookbehind
(?<=c )ab
(? <!c )ab
matches "ab" i f i t ’ s part of "abc "
matches "ab" i f not followed by a " c "
matches "ab" i f i t ’ s part of "cab "
matches "ab" i f not behind a " c "
Regular Expression – Rules for Pattern Matching
Pattern analysis will start at the beginning of the string.
If pattern matches, analysis will continue as long as the pattern is still matching
(greedy).
Pattern matching behavior can be changed to non-greedy by using the "?" behind the
quantifier.
⇒ the pattern analysis stops at the first (minimal) matching
>>> r e . f i n d a l l ( r " Py. * o n " , " Python . . . Python " )
[ ’ Python . . . Python ’ ]
>>> r e . f i n d a l l ( r " Py. * ? o n " , " Python . . . Python " )
[ ’ Python ’ , ’ Python ’ ]
Regular Expressions – Groups
() brackets in a pattern create a group
Group name is numbered serially (starting with 1)
The first 99 groups ( 1 - 99 ) can be referenced in the same pattern
Patterns can be combined with logical or ( | ) inside a group
>>> r e . f i n d a l l ( r " (  w+) 1" , " Py Py abc Test T e s t " )
[ ’ Py’ , ’ Test ’ ]
>>>
>>> r e . f i n d a l l ( r " ( [ A- Za - z ] + |  d + ) " , " uid =2765( zdv124) " )
[ ’ ui d’ , ’ 2765’ , ’ z dv’ , ’ 124’ ]
>>>
>>> r e. f i ndal l ( r " ( [ . * ? ] | <. * ? >) " , " [ hi ] s <b>s d<hal >" )
[ ’ [ h i ] ’ , ’ < b > ’ , ’ <hal > ’ ]
3/4/2023
Regular Expressions – Group Usage
re.*
Some methods return a re.MatchObject
⇒ contain captured groups
re_groups.py
t e x t = " adm06: x :706 :1000 : S t . Graf : / home/ adm06: / bin / bash "
grp = r e . match (
r " ^( [ a - z0 -9 ] + ) : x : [ 0 -9 ] + : [ 0 -9 ] + : ( . + ) : . + : . + $ " , t e x t )
i f ( gr p) :
pr i nt ( " f ound: " , gr p. gr oups ( ) )
pr i nt ( " us er I D=" , gr p. gr oup( 1) )
pr i nt ( " nam
e =" , gr p. gr oup( 2) )
$ pyt hon3 r e_ gr oups . py
f ound: ( ’ adm
06’ , ’ St . Gr af ’ )
user ID= adm06
nam
e = St . Gr af
Regular Expressions – Matching Flags
Special flags can change behavior of the pattern matching
r e . I : Case insensitive pattern matching
re.M : ˆ or. $ will match at beginning/end of each line
(not only at the beginning/end of string)
re.S : . also matches newline ( n )
>>> r e. f i ndal l ( " ^abc " , " Abc nabc " )
[ ]
>>> r e. f i ndal l ( " ^abc " , " Abc nabc " , r e. I )
[ ’ A b c ’ ]
>>> r e. f i ndal l ( " ^abc " , " Abc nabc " , r e. I | r e. M)
[ ’ A b c ’ , ’ abc ’ ]
>>> r e. f i ndal l ( " ^Abc . " , " Abc nabc " )
[ ]
>>> r e. f i ndal l ( " ^Abc . " , " Abc nabc " , r e. S)
[ ’ Abcn ’ ]
Regular Expressions – Methods (I)
findall: Simple pattern matching
⇒ list of strings (hits)
>>> r e. f i ndal l ( r " [ . * ? ] " , " a[ bc ] g[ hal ] def " )
[ ’ [ b c ] ’ , ’ [ h a l ] ’ ]
sub: Query replace ⇒ new (replaced) string
>>> r e. s ub( r " [ . * ? ] " , " ! " , " a[ bc ] g[ hal ] def " )
’ a ! g ! d e f ’
search: Find first match of the pattern
re.MatchObject
⇒ returns or None
i f r e . search ( r "  [ . * ?  ] " , " a[ b c ] g[ h a l ] d e f " ) :
pr i nt ( " pat t er n m
at c hed! " )
Regular Expressions – Methods (II)
match: Starts pattern matching at beginning of the string
re.MatchObject
⇒ returns or None
t e x t = " adm06: x :706 :1000 : S t . Graf : / home/ adm06: / bin / bash "
grp = r e . match (
" ( [ a - z0 -9 ] + ) : x : [ 0 -9 ] + : [ 0 -9 ] + : ( . + ) : . + : . + $ " , t e x t )
compile: Regular expressions can be pre-compiled
⇒ gain performance on reusing these RegExp multiple times
(e.g. in loops)
>>> pat t er n = r e. c om
pi l e( r " [ . * ? ] " )
>>> pat t er n. f i ndal l ( " a[ bc ] g[ hal ] def " )
[ ’ [ bc ] ’ , ’ [ hal ] ’ ]

More Related Content

PPT
Python tutorialfeb152012
PPTX
funadamentals of python programming language (right from scratch)
PPT
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
Introduction_to_Python_operators_datatypes.pptx
PPTX
Python Revision Tour.pptx class 12 python notes
PPTX
Python PPT2
PDF
Introduction To Programming with Python
Python tutorialfeb152012
funadamentals of python programming language (right from scratch)
Python Workshop - Learn Python the Hard Way
Introduction_to_Python_operators_datatypes.pptx
Python Revision Tour.pptx class 12 python notes
Python PPT2
Introduction To Programming with Python

Similar to Python cheatsheat.pdf (20)

PPTX
Python programming workshop
PPTX
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
PPTX
Python programming
PDF
Processing data with Python, using standard library modules you (probably) ne...
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
PPTX
Learning python
PPTX
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
PPTX
Learn more about the concepts of Data Types in Python
PPTX
Programming Basics.pptx
PDF
ppt_pspp.pdf
PPTX
python_computer engineering_semester_computer_language.pptx
PPT
Python course in_mumbai
PPT
Python course in_mumbai
PPTX
PPT
02python.ppt
Python programming workshop
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
Python programming
Processing data with Python, using standard library modules you (probably) ne...
Learning python
Learning python
Learning python
Learning python
Learning python
Learning python
Learning python
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
Learn more about the concepts of Data Types in Python
Programming Basics.pptx
ppt_pspp.pdf
python_computer engineering_semester_computer_language.pptx
Python course in_mumbai
Python course in_mumbai
02python.ppt
Ad

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
KodekX | Application Modernization Development
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
cuic standard and advanced reporting.pdf
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
Approach and Philosophy of On baking technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Unlocking AI with Model Context Protocol (MCP)
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Understanding_Digital_Forensics_Presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Ad

Python cheatsheat.pdf

  • 1. 3/4/2023 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Slide 17 Numerical Data Types int : integer numbers (infinite) float : corresponds to double in C complex : complex numbers ( j is the imaginary unit) a = 1 c = 1.0 c = 1e0 d = 1 + 0j Slide 18 Operators on Numbers Basic arithmetics: + , - , * , / hint: Python 2 ⇒ 1/2 = 0 Python 3 ⇒ 1/2 = 0.5 Div and modulo operator: // , %, divmod(x, y) Absolute value: abs(x) Rounding: round(x) Conversion: int(x) , float(x) , complex(re [ , im=0]) Conjugate of a complex number: x.conjugate() Power: x ** y , pow(x, y) Result of a composition of different data types is of the “bigger” data type. Slide 19 Bitwise Operation on Integers Operations: AND: x &y OR: x | y exclusive OR (XOR) : x ˆ y invert: ~x shift right n bits: x >> n shift left n bits: x << n Use bin(x) to get binary representation string of x . >>> pr i nt ( bi n( 6) , bi n( 3) ) 0b110 0b11 >>> 6 & 3 2 >>> 6 | 3 7 >>> 6 ^ 3 5 >>> ~0 -1 >>> 1 << 3 8 >>> pow( 2, 3) 8 >>> 9 >> 1 4 >>> pr i nt ( bi n( 9) , bi n( 9>>1) ) 0b1001 0b100 Slide 20
  • 2. 3/4/2023 Strings Data type: str s = ’spam’ , s = "spam" Multiline strings: s = """spam""" s = r"spnam" str(1.0) No interpretation of escape sequences: Generate strings from other data types: >>> s = """hello ... world""" >>> pr i nt ( s ) h e l l o world >>> pr i nt ( " sp nam " ) sp am >>> pr i nt ( r " spnam" ) # or: print("spnam") spnam Slide 21 String Methods Count appearance of substrings: s.count(sub [ , start[, end]]) Begins/ends with a substring? s.startswith(sub[, start[, end]]) , s.endswith(sub[, start[, end]]) All capital/lowercase letters: s.upper() , s.lower() Remove whitespace: s.strip([chars]) Split at substring: s.split([sub [,maxsplit]]) Find position of substring: s.index(sub[, start[, end]]) Replace a substring: s.replace(old, new[, count]) More methods: help(str) , dir(str) Slide 22 Lists Data type: l i s t s = [1, "spam", 9.0, 42] , s = [ ] Append an element: s.append(x) Extend with a second list: s.extend(s2) Count appearance of an element: s.count(x) Position of an element: s.index(x[, min[, max]]) Insert element at position: s.insert(i, x) Remove and return element at position: s.pop([i]) Delete element: s.remove(x) Reverse list: s.reverse() Sort: s.sort([cmp[, key[, reverse]]]) Sum of the elements: sum(s) Slide 23 Tuple Data type: tuple s = 1, "spam", 9.0, 42 s = (1, "spam", 9.0, 42) Constant list Count appearance of an element: s.count(x) Position of an element: s.index(x[, min[, max]]) Sum of the elements: sum(s) Slide 24
  • 3. 3/4/2023 Tuple Data type: tuple s = 1, "spam", 9.0, 42 s = (1, "spam", 9.0, 42) Constant list Count appearance of an element: s.count(x) Position of an element: s.index(x[, min[, max]]) Sum of the elements: sum(s) Multidimensional tuples and lists List and tuple can be nested (mixed): >>> A=( [ 1, 2, 3] , ( 1, 2, 3) ) >>> A ( [ 1, 2, 3] , ( 1, 2, 3) ) >>> A[ 0] [ 2] =99 >>> A ( [ 1, 2, 99] , ( 1, 2, 3) ) Slide 24 Lists, Strings and Tuples Lists are mutable Strings and tuples are immutable No assignment s [ i ] = . . . No appending and removing of elements Functions like x.upper() return a new string! >>> s 1 = " s pam" >>> s 2 = s1. upper ( ) >>> s1 ’ s pam’ >>> s2 ’ SPAM’ Slide 25 Operations on Sequences Strings, lists and tuples have much in common: They are sequences. Does/doesn’t s contain an element? x in s , x not in s Concatenate sequences: s + t Multiply sequences: n * s , s * n i-th element: s [ i] , i-th to last element: s [ - i ] Subsequence (slice): s [ i : j ] , with step size k: s [ i : j : k ] Subsequence (slice) from beginning/to end: s [ : - i ] , s [ i : ] , s [ : ] Length (number of elements): len(s) Smallest/largest element: min(s) , max(s) Assignments: → a = s[0] , (a , b, c) = s b = s[1] , c = s[2] Slide 26 Indexing in Python positive index 0 1 2 3 4 5 6 7 8 9 10 element P y t h o n K u r s negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 >>> kur s = " Pyt hon Kur s " >>> kur s [ 2: 2] >>> kur s [ 2: 3] t >>> kur s [ 2] t >>> kur s [ - 4: - 1] Kur >>> kur s [ - 4: ] Kurs >>> kur s [ - 6: - 8: - 1] no Slide 27
  • 4. 3/4/2023 Boolean Values Data type bool: True , False Values that are evaluated to False : None (data type NoneType ) False 0 (in every numerical data type) Empty strings, lists and tuples: ” , [ ] , () Empty dictionaries: {} Empty sets set() All other objects of built-in data types are evaluated to True ! >>> bool ( [ 1, 2, 3] ) True >>> b o o l ( " " ) F al se Slide 28 References Every object name is a reference to this object! An assignment to a new name creates an additional reference to this object. s2 = s1[:] Hint: copy a list with or s2 = list(s1) Operator is compares two references (identity), == operator compares the contents of two objects Assignment: different behavior depending on object type Strings, numbers (simple data types): create a new object with new value Lists, dictionaries, ...: the original object will be changed Slide 29 Reference - Example >>> x=1 >>> y=x >>> x i s y True >>> y=2 >>> x i s y False x 1 Slide 30 Reference - Example >>> x=1 >>> y=x >>> x i s y True >>> y=2 >>> x i s y False x y 1 Slide 30
  • 5. 3/4/2023 Reference - Example >>> x=1 >>> y=x >>> x i s y True >>> y=2 >>> x i s y False x y 1 2 Slide 30 Reference - Example >>> x=1 >>> y=x >>> x i s y True >>> y=2 >>> x i s y False x y 1 2 >>> s1 = [ 1, 2, 3, 4] >>> s2 = s1 >>> s2[1] = 17 >>> s1 [ 1, 17, 3, 4] >>> s2 [ 1, 17, 3, 4] 1 2 3 4 s1 s2 Slide 30 Reference - Example >>> x=1 >>> y=x >>> x i s y True >>> y=2 >>> x i s y False x y 1 2 >>> s1 = [ 1, 2, 3, 4] >>> s2 = s1 >>> s2[1] = 17 >>> s1 [ 1, 17, 3, 4] >>> s2 [ 1, 17, 3, 4] 1 17 3 4 s1 s2 Slide 30 Groups 1 2 3 4 5 6 7 8 Slide 31
  • 6. 3/4/2023 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Slide 32 The If Statement i f a == 3: pr i nt ( " Aha ! " ) Blocks are defined by indentation! ⇒Style Guide for Python Standard: Indentation with four spaces i f a == 3: pr i nt ( " s pam" ) e l i f a == 10: pr i nt ( " eggs " ) e l i f a == - 3 : pr i nt ( " bac on" ) el s e : pr i nt ( " s om et hi ng el s e " ) Slide 33 Relational Operators Comparison of content: == , < , > , <= , >= , != Comparison of object identity: a is b , a is not b And/or operator: a and b , a or b Chained comparison: a <= x < b , a == b == c , .. . Negation: not a i f not ( a==b) and ( c <3) : pass pass Hint: is a No Operation (NOOP) function Slide 34 For Loops fo r i in range ( 1 0 ) : pr i nt ( i ) # 0, 1, 2, 3, ..., 9 f or i i n r ange ( 3, 10) : pr i nt ( i ) # 3, 4, 5, ..., 9 f or i i n r ange ( 0, 10, 2) : pr i nt ( i ) # 0, 2, 4, 6, 8 el s e : pr i nt ( " Loop c om pl et ed. " ) End loop prematurely: break Next iteration: continue else is executed when loop didn’t end prematurely Slide 35
  • 7. 3/4/2023 For Loops (continued) Iterating directly over sequences (without using an index): f or i t em i n [ " s pam" , " eggs " , " bac on" ] : p r i n t ( item ) range The function can be used to create a list: >>> l i s t ( r ange ( 0, 10, 2) ) [ 0, 2, 4, 6, 8] If indexes are necessary: f or ( i , c har ) i n enum er at e( " hel l o wor l d" ) : p r i n t ( i , c har) Slide 36 While Loops i = 0 while i < 10: i += 1 break continue and work for while loops, too. Substitute for do-while loop: whi l e Tr ue : # important code i f c ondi t i on: break Slide 37 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Functions def add( a, b) : """Returns the sum of a and b.""" mysum= a + b return mysum >>> r es ul t = add( 3, 5) >>> pr i nt ( r es ul t ) 8 >>> hel p( add) Help on fun c ti o n add in module _ _ m a i n _ _ : add( a, b) Returns the sum o f a and b .
  • 8. 3/4/2023 Return Values and Parameters Functions accept arbitrary objects as parameters and return values Types of parameters and return values are unspecified Functions without explicit return value return None my_program.py def hel lo _ wo rl d ( ) : pr i nt ( " Hel l o W or l d! " ) a = hel l o_ wor l d( ) pr i nt ( a) $ pyt hon3 m y_ pr ogr am . py Hel l o W or l d! None Multiple Return Values Multiple return values are realised using tuples or lists: def f oo( ) : a = 17 b = 42 return ( a , b) r et = f oo( ) ( x , y) = f oo( ) Optional Parameters – Default Values Parameters can be defined with default values. Hint: It is not allowed to define non-default parameters after default parameters plot_lines.py def f l i ne ( x, m =1, b=0) : # f(x) = m*x + b r et ur n m * x + b fo r i in range ( 5 ) : pr i nt ( f l i ne ( i ) , end=" " ) #force newline pr i nt ( ) fo r i in range ( 5 ) : pr i nt ( f l i ne ( i , - 1, 1) , end=" " ) $ pyt hon3 pl ot _ l i nes . py 0 1 2 3 4 1 0 -1 -2 -3 end Hint: in print defines the last character, default is linebreak Positional Parameters pr i nt ( " Per s on: pr i nt ( " Age : " , nam e ) " , age , " year s " ) Parameters can be passed to a function in a different order than specified: displayPerson.py def pr i nt Cont ac t ( nam e , age , l oc at i on) : pr i nt ( " Addr es s : " , l oc at i on) p r i n t C o n t a c t ( name=" Peter Pan" , l o c a t i o n =" Neverland " , age =10) $ pyt hon3 di s pl ayPer s on. py Per s on: Age: Peter Pan 10 years Address: Neverland
  • 9. 3/4/2023 Functions are Objects Functions are objects and as such can be assigned and passed on: >>> a = f l o a t >>> a ( 22) 22.0 >>> def f oo( f kt ) : . . . pr i nt ( f kt ( 33) ) . . . >>> f oo( f l oat ) 33.0 >>> f oo( s t r ) 33 >>> f oo( c om pl ex) ( 33+0j ) Online Help: Docstrings Can be used in function, modul, class and method definitions Is defined by a string as the first statement in the definition hel p (. ..) on python object returns the docstring Two types of docstrings: one-liners and multi-liners def c om pl ex( r eal =0. 0, i m ag =0. 0) : """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ . . . Functions & Modules Functions thematically belonging together can be stored in a separate Python file. (Same for objects and classes) This file is called module and can be loaded in any Python script. Multiple modules available in the Python Standard Library (part of the Python installation) import <filename> Command for loading a module: (filename without ending .py) import math s = m at h. s i n( m at h. pi ) More information for standard modules and how to create your own module see chapter Modules and Packages on slide 91 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook
  • 10. 3/4/2023 String Formatting Format string + class method x.format() “replacement fields”: curly braces around optional arg_name (default: 0,1,2,...) pr i nt ( " The ans wer i s { 0: 4d} " . f or m at ( 42) ) ’ The ans wer i s 42’ s = " { 0 } : {1 :08 . 3 f } " . fo rmat( " spam" , 3. 14) ’ s pam: 0003. 140’ format purpose default: string m.nf floating point: m filed size, n digits after the decimal point (6) m.ne floating point (exponential): m filed size, 1 digit before and n digits behind the decimal point (default: 6) m.n% percentage: similar to format f, value ∗ 100 with finalizing ’%’ md Integer number: m field size (0m ⇒leading “0”) format d can be replaced by b (binary), o (octal) or x (hexadecimal) Literal String Interpolation (f-strings) Provides a way to embed expressions inside string literals, using a minimal syntax Is a literal string, prefixed with ’f’, which contains expressions inside braces Expressions are evaluated at runtime and replaced with their values. >>> nam e = " Mar t i n" >>> age = 50 >>> f " My name i s { name} and my age next year i s { age +1}" ’ Myname i s Martin and myage next year i s 51’ >>> val ue = 12. 345 >>> f " val ue ={ val ue : 5. 2f } " ’ val ue =12. 35’ Hint: Since Python 3.6! String Formatting (deprecated, Python 2 only) String formatting similar to C: pr i nt " The ans wer i s % 4i . " % 42 s = " % s : % 08. 3f " % ( " s pam" , 3. 14) Integer decimal: d, i Integer octal: o Integer hexadecimal: x, X Float: f, F Float in exponential form: e, E, g, G Single character: c String: s Use % %to output a single %character. Command Line Input User input in Python 3: us er _ i nput = i nput ( " Type s om et hi ng: " ) User input in Python 2: us er_ i npu t = raw _ inp ut(" Type something : " ) Hint: In Python 2 is input("...") ⇐⇒ eval(raw_input("...")) Command line parameters: params.py import sys pr i nt ( s ys . ar gv) $ pyt hon3 par am s . py s pam[ ’ par am s . py ’ , ’ spam’ ]
  • 11. 3/4/2023 Files f i l e1 = open( " s pam. t xt " , " r " ) f i l e2 = open( " /t m p/eggs . j s on" , " wb" ) Read mode: r Write mode (new file): w Write mode, appending to the end: a Handling binary files: e.g. rb Read and write (update): r+ f or l i ne i n f i l e1: pr i nt ( l i ne ) Operations on Files Read: f.read([size]) Read a line: f.readline() Read multiple lines: f.readlines([sizehint]) Write: f.write(str) Write multiple lines: f.writelines(sequence) Close file: f.close() f i l e1 = open( " t es t . t xt " , " w" ) l i nes = [ " s pamn" , " eggs n" , " hamn" ] f i l e1. wr i t el i nes ( l i nes ) f i l e1. c l os e ( ) Python automatically converts n into the correct line ending! The with statement File handling (open/close) can be done by the context manager with . (⇒section Errors and Exceptions on slide 65). wi t h open( " t es t . t xt " ) as f : fo r l i n e in f : pr i nt ( l i ne ) with After finishing the block the file object is closed, even if an exception occurred inside the block. Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook
  • 12. 3/4/2023 Syntax Errors, Indentation Errors Parsing errors: Program will not be executed. Mismatched or missing parenthesis Missing or misplaced semicolons, colons, commas Indentation errors add.py pr i nt ( " I ’ m r unni ng . . . " ) def add( a, b) return a + b $ pyt hon3 add. py Fi l e " add. py" , l i ne 2 def add( a, b) ^ Synt axEr r or : i nval i d s ynt ax Exceptions Exceptions occur at runtime: import math pr i nt ( " I ’ m r unni ng . . . " ) m at h. f oo( ) pr i nt ( " I ’ m s t i l l r unni ng. . . " ) error.py $ pyt hon3 er r or . py I ’ m r unni ng . . . Tr ac ebac k ( m os t r ec ent c al l l as t ) : Fi l e " er r or . py" , l i ne 3, i n <m odul e > m at h. f oo( ) A t t r i b u t e Error : module ’ math ’ has no a t t r i b u t e ’ f oo ’ Handling Exceptions (1) t r y: s = i nput ( " Ent er a num ber : " ) num ber = f l oat ( s ) exc ept Val ueEr r or : pr i nt ( " That ’ s not a num ber ! " ) except try block is executed when the code in the block throws an according exception Afterwards, the program continues normally Unhandled exceptions force the program to exit. Handling different kinds of exceptions: exc ept ( Val ueEr r or , TypeEr r or , Nam eEr r or ) : Built-in exceptions: http://docs.python.org/library/exceptions.html Handling Exceptions (2) t r y: s = i nput ( " Ent er a num ber : " ) num ber = 1/ f l oat ( s ) exc ept Val ueEr r or : pr i nt ( " That ’ s not a num ber ! " ) exc ept Zer oDi vi s i onEr r or : p r i n t ( " You can ’ t di vid e by zero ! " ) e x c e p t : pr i nt ( " Oops , what ’ s happened? " ) except Several statements for different exceptions except Last can be used without specifying the kind of exception: Catches all remaining exceptions Careful: Can mask unintended programming errors!
  • 13. 3/4/2023 Handling Exceptions (3) else is executed if no exception occurred finally is executed in any case t r y: f = open( " s pam " ) except I OE rro r: pr i nt ( " Cannot open f i l e " ) e l s e : pr i nt ( f . r ead( ) ) f . c l os e ( ) f i nal l y: pr i nt ( " End of t r y. " ) Exception Objects Access to exception objects: EnvironmentError ( IOError , OSError ): int , Exception object has 3 attributes ( str , str ) Otherwise: Exception object is a string spam_open.py t r y: f = open( " s pam " ) except IOError as e : pr i nt ( e. er r no , e. f i l enam e , e. s t r er r or ) p r i n t ( e) $ pyt hon3 s pam _ open. py 2 spam No such f i l e or d i r e c t o r y [ Er r no 2] No s uc h f i l e or di r ec t or y: ’ s pam’ Exceptions in Function Calls draw() rectangle() line() Exception! Function calls another function. That function raises an exception. Is exception handled? No: Pass exception to calling function. Raising Exceptions opening f i l e ! " ) Passing exceptions on: t r y: f = open( " s pam " ) except I OE rro r: pr i nt ( " Pr obl em whi l e r a i s e Raising exceptions: def gaus s _ s ol ver ( m at r i x) : # Important code r ai s e Val ueEr r or ( " Si ngul ar m at r i x" )
  • 14. 3/4/2023 Exceptions vs. Checking Values Beforehand Exceptions are preferable! def s quar e( x ) : i f t ype ( x) == i nt or t ype( x) == f l oat : return x ** 2 el s e : return None What about other numerical data types (complex numbers, own data types)? Better: Try to compute the power and catch possible exceptions! → Duck-Typing Caller of a function might forget to check return values for validity. Better: Raise an exception! Slide 64 Exceptions vs. Checking Values Beforehand Exceptions are preferable! t ype ( x) == f l oat : def s quar e( x ) : i f t ype ( x) == i nt or return x ** 2 el s e : return None def s quar e( x ) : return x ** 2 . . . t r y: r es ul t = s quar e( val ue ) exc ept TypeEr r or : pr i nt ( " ’ { 0} ’ : I nval i d t ype " . f or m at ( val ue ) ) Slide 64 The with Statement Some objects offer context management 3 , which provides a more convenient way to try . . . finally write blocks: wi t h open( " t es t . t xt " ) as f : fo r l i n e in f : pr i nt ( l i ne ) with After the block the file object is guaranteed to be closed properly, no matter what exceptions occurred within the block. exit ( . . . ) 3 Class method enter ( sel f) will be executed at the beginning and class method at the end of the context Slide 65 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Slide 66
  • 15. 3/4/2023 Sets Set: unordered, no duplicated elements s = {"a", "b", "c"} alternative s = set([sequence]) , required for empty sets. Constant set: s = frozenset([sequence]) e.g. empty set: empty = frozenset() Subset: s.issubset(t) , s <= t , strict subset: s < t Superset: s.issuperset(t) , s >= t , strict superset: s > t Union: s.union(t) , s | t Intersection: s.intersection(t) , s & t Difference: s.difference(t) , s - t Symmetric Difference: s.symmetric_difference(t) , s ˆ t Copy: s.copy() As with sequences, the following works: x in s , len(s) , for x in s , s.add(x) , s.remove(x) Slide 67 Dictionaries Other names: Hash, Map, Associative Array Mapping of key → value Keys are unordered >>> s t or e = { " s pam" : 1, " eggs " : 17} >>> s t or e [ " eggs " ] 17 >>> s t or e [ " bac on" ] = 42 >>> st o re { ’ eggs ’ : 17, ’ bac on’ : 42, ’ s pam’ : 1} Iterating over dictionaries: f or key i n s t or e : pr i nt ( key , s t or e [ key ] ) Compare two dictionaries: store == pool Not allowed: > , >= , < , <= Slide 68 Operations on Dictionaries Delete an entry: del(store[key]) Delete all entries: store.clear() Copy: store.copy() Does it contain a key? key in store Get an entry: store.get(key[, default]) Remove and return entry: store.pop(key[, default]) Remove and return arbitrary entry: store.popitem() Slide 69 Operations on Dictionaries Delete an entry: del(store[key]) Delete all entries: store.clear() Copy: store.copy() Does it contain a key? key in store Get an entry: store.get(key[, default]) Remove and return entry: store.pop(key[, default]) Remove and return arbitrary entry: store.popitem() Views on Dictionaries Create a view: items() , keys() and values() List of all (key, value) tuples: store.items() store.keys() List of all keys: List all values: store.values() Caution: Dynamical since Python 3 Slide 69
  • 16. 3/4/2023 Views Behavior: Python 2.X versus Python 3.X Python 2 (static) >>> m di c t ={ " a" : 2, " d" : 5} >>> mdict { ’ a’ : 2, ’ d’ : 5} >>> s =m di c t . i t em s ( ) >>> fo r i in s : pr i nt ( i ) ( ’ a ’ , 2) ( ’ d ’ , 5) >>> m di c t [ ’ a’ ] =- 1 >>> mdict { ’ a’ : - 1, ’ d’ : 5} >>> fo r i in s : pr i nt ( i ) ( ’ a ’ , 2) ( ’ d ’ , 5) Python 3 (dynamic) >>> m di c t ={ " a" : 2, " d" : 5} >>> mdict { ’ a’ : 2, ’ d’ : 5} >>> s =m di c t . i t em s ( ) >>> fo r i in s : pr i nt ( i ) ( ’ a ’ , 2) ( ’ d ’ , 5) >>> m di c t [ ’ a’ ] =- 1 >>> mdict { ’ a’ : - 1, ’ d’ : 5} >>> fo r i in s : pr i nt ( i ) ( ’ a ’ , -1) ( ’ d ’ , 5) Slide 70 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Slide 71 Object Oriented Programming (OOP) So far: procedural programming Data (values, variables, parameters, . ..) Functions taking data as parameters and returning results Alternative: Group data and functions belonging together to form custom data types → Extensions of structures in C/Fortran Slide 72 Using Simple Classes as Structs my_point.py c l a s s P o i n t : pass p = Poi nt ( ) p. x = 2. 0 p. y = 3. 3 Class: Custom date type (here: Point ) Object: Instance of a class (here: p ) Attributes (here x , y ) can be added dynamically pass Hint: is a No Operation (NOOP) function Slide 73
  • 17. 3/4/2023 Classes - Constructor my_point.py c l a s s P o i n t : def _ _ i ni t _ _ ( sel f , x , y) : s el f . x = x s el f . y = y p = Poi nt ( 2. 0, 3. 0) pr i nt ( p. x , p. y) p. x = 2. 5 p. z = 42 init : Is called automatically after creating an object Slide 74 Methods on Objects my_point.py import math c l a s s P o i n t : def _ _ i ni t _ _ ( sel f , x , y) : s el f . x = x s el f . y = y def nor m ( s el f ) : n= math. s q r t ( s e l f . x**2 + s e l f . y**2) return n p = Poi nt ( 2. 0, 3. 0) pr i nt ( p. x , p. y, p. nor m( ) ) Method call: automatically sets the object as first parameter → traditionally called self Careful: Overloading of methods not possible! Slide 75 Converting Objects to Strings Default return value of s t r ( . . . ) for objects of custom classes: >>> p = Poi nt ( 2. 0, 3. 0) >>> pr i nt ( p) # --> print(str(p)) <_ _ m a i n _ _ . Point in stan c e at 0x402d7a8c > Slide 76 Converting Objects to Strings Default return value of s t r ( . . . ) for objects of custom classes: >>> p = Poi nt ( 2. 0, 3. 0) >>> pr i nt ( p) # --> print(str(p)) <_ _ m a i n _ _ . Point in stan c e at 0x402d7a8c > This behaviour can be overwritten: my_point.py c l a s s P o i n t : [ . . . ] def _ _ s t r _ _ ( s el f ) : return " ( { 0 } , { 1 } ) " . format( s e l f . x , s e l f . y) >>> pr i nt ( p) ( 2. 0, 3. 0) Slide 76
  • 18. 3/4/2023 Comparing Objects == Default: checks for object identity of custom objects. >>> p1 = Poi nt ( 2. 0, 3. 0) >>> p2 = Poi nt ( 2. 0, 3. 0) >>> p1 == p2 F al se Slide 77 Comparing Objects == Default: checks for object identity of custom objects. >>> p1 = Poi nt ( 2. 0, 3. 0) >>> p2 = Poi nt ( 2. 0, 3. 0) >>> p1 == p2 F al se This behaviour can be overwritten: c l a s s P o i n t : [ . . . ] def _ _ eq_ _ ( s el f , ot her ) : r et ur n ( s el f . x == ot her . x) and ( s el f . y == ot her . y) my_point.py equal values identity >>> p1 == p2 # Check for True >>> p1 i s p2 # Check for F al se Slide 77 Operator overloading More relational operators: < : l t ( s e l f, other) <= le ( s e l f, other) : != : ne ( s e l f , other) > : gt ( s e l f , other) >= : ge ( s e l f , other) Numeric operators: add ( s e l f , other) sub ( s e l f , other) + : - : * : ... mul ( s e l f , other) Emulating Existing Data Types Classes can emulate built-in data types: Numbers: arithmetics, int(myobj) , float(myobj) , .. . Functions: myobj(...) Sequences: len(myobj) , myobj[...] , x in myobj , ... Iteratores: for i in myobj See documentation: http://docs.python.org/3/reference/datamodel.html
  • 19. 3/4/2023 Class Variables Have the same value for all instances of a class: c l a s s P o i n t : count = 0 # Count all point objects my_point.py def _ _ i ni t _ _ ( sel f , x , y) : Poi nt . c ount += 1 #self.__class__.count += 1 [ . . . ] >>> p1 = Poi nt ( 2, 3) ; p2 = Poi nt ( 3, 4) >>> p1. c ount 2 >>> p2. c ount 2 >>> Poi nt . c ount 2 Class Methods and Static Methods c l as s Spam : s pam = " I don’ t l i ke s pam . " @ c l as s m et hod def c m et hod( c l s ) : pr i nt ( c l s . s pam) @ s t at i c m et hod def s m et hod( ) : pr i nt ( " Bl ah bl ah. " ) spam.py Spam . c m et hod( ) Spam . s m et hod( ) s = Spam( ) s . c m et hod( ) s . s m et hod( ) Inheritance (1) There are often classes that are very similar to each other. Inheritance allows for: Hierarchical class structure (is-a-relationship) Reusing of similar code Example: Different types of phones Phone Mobile phone (is a phone with additional functionality) Smart phone (is a mobile phone with additional functionality) Inheritance (2) c l as s Phone: def c al l ( s el f ) : pass c l as s M obi l ePhone( Phone) : def s end_ t ext ( s el f ) : pass MobilePhone now inherits methods and attributes from Phone. h = M obi l ePhone ( ) h. c al l ( ) # inherited from Phone h. s end_ t ext ( ) # own method
  • 20. 3/4/2023 Overwriting Methods Methods of the parent class can be overwritten in the child class: c l as s M obi l ePhone( Phone) : def c al l ( s el f ) : s el f . f i nd_ s i gnal ( ) Phone. c al l ( s el f ) Multiple Inheritance Classes can inherit from multiple parent classes. Example: SmartPhone is a mobile phone SmartPhone is a camera c l a s s SmartPhone ( MobilePhone , Camera ) : pass h = Sm ar t Phone ( ) h. c al l ( ) # inherited from MobilePhone h. t ake_ phot o( ) # inherited from Camera Attributes are searched for in the following order: MobilePhone SmartPhone , MobilePhone , parent class of (recursively), Camera , parent class of Camera (recursively). Private Attributes / Private Class Variables There are no private variables or private methods in Python. Convention: Mark attributes that shouldn’t be accessed from outside with an underscore: _foo . foo To avoid name conflicts during inheritance: Names of the form are replaced with _classname foo : c l as s Spam : _ _ egg s = 3 _bacon = 1 beans = 5 >>> di r ( Spam ) >>> [ ’ _Spam__eggs ’ , ’ _ _ d o c _ _ ’ , ’ __module__ ’ , ’ _bacon ’ , ’ beans ’ ] Classic (old Style) Classes The only class type until Python 2.1 In Python 2 default class New Style Classes Unified class model (user-defined and build-in) Descriptores (getter, setter) The only class type in Python 3 Available as basic class in Python 2: object
  • 21. 3/4/2023 Properties (1) If certain actions (checks, conversions) are to be executed while accessing attributes, use getter and setter: c l as s Spam : def _ _ i ni t _ _ ( s el f ) : s el f . _ val ue = 0 def get _ val ue( s el f ) : r et ur n s el f . _ val ue def s et _ val ue( sel f , val ue ) : i f value <= 0: s el f . _ val ue = 0 el s e : s el f . _ val ue = val ue val ue = pr oper t y( get _ val ue , s et _ val ue) Properties (2) Properties can be accessed like any other attributes: >>> s = Spam( ) # set_value(6) # get_value() # set_value(-6) # get_value() >>> s . val ue = 6 >>> s . val ue 6 >>> s . val ue = - 6 >>> s . val ue 0 Getter and setter can be added later without changing the API _value Access to still possible Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Importing Modules Reminder: Functions, classes and object thematically belonging together are grouped in modules. import math s = m at h. s i n( m at h. pi ) import math as m s = m . s i n( m . pi ) f r om m at h i m por t pi as PI , s i n s = si n ( P I ) from math import * s = s i n( pi ) Online help: dir(math) , help(math)
  • 22. 3/4/2023 Creating a Module (1) Every Python script can be imported as a module. my_module.py """My first module: my_module.py""" def add( a, b) : """Add a and b.""" return a + b pr i nt ( add( 2, 3) ) >>> import my_module 5 >>> m y_ m odul e. add( 17, 42) 59 Top level instructions are executed during import! Creating a Module (2) If instructions should only be executed when running as a script, not importing it: my_module.py def add( a, b) : return a + b def m ai n( ) : pr i nt ( add( 2, 3) ) i f _ _ nam e_ _ == " _ _ m ai n_ _ " : m ai n( ) Useful e.g. for testing parts of the module. Creating a Package Modules can be grouped into hierarchically structured packages. numeric init .py linalg init .py decomp.py eig.py solve.py fft init .py ... Packages are subdirectories In each package directory: init .py (may be empty) import numeric num er i c . f oo( ) # from __init__.py num er i c . l i nal g . ei g . f oo( ) f r om num er i c . l i nal g i m por t ei g ei g. f oo( ) Modules Search Path Modules are searched for in (see sys.path ): The directory of the running script Directories in the environment variable PYTHONPATH Installation-dependent directories >>> import sys >>> s ys . pat h [ ’ ’ , ’ /us r / l i b/ pyt hon37. z i p’ , ’ /us r / l i b64/ pyt hon3. 7’ , ’ / usr/ l ib 64 / python3.7 / p lat - l i n u x ’ , . . . ]
  • 23. 3/4/2023 Python’s Standard Library „Batteries included“: comprehensive standard library for various tasks Mathematics: math Constants: e , pi Round up/down: floor(x) , ceil(x) Exponential function: exp(x) Logarithm: log(x[, base]) , log10(x) Power and square root: pow(x, y) , sqrt(x) Trigonometric functions: sin(x) , cos(x) , tan(x) radians(x) Conversion degree ↔radiant: degrees(x) , >>> import math >>> m at h. s i n( m at h. pi ) 1. 2246063538223773e - 16 >>> m at h. c os ( m at h. r adi ans ( 30) ) 0. 86602540378443871 Random Numbers: random Random integers: randint(a, b) , randrange([start,] stop[, step]) Random floats (uniform distr.): random() , uniform(a, b) Other distibutions: expovariate(lambd) , gammavariate(alpha, beta) , gauss(mu, sigma) , .. . Random element of a sequence: choice(seq) Several unique, random elements of a sequence: sample(population, k) shuffle(seq[, random]) Shuffled sequence: >>> import random wor l d! " ) >>> s = [ 1, 2, 3, 4, 5] >>> r andom . s huf f l e( s ) >>> s [ 2, 5, 4, 3, 1] >>> r andom . c hoi c e( " Hel l o ’ e ’ Time Access and Conversion: time Classical time() functionality int Time class type is a 9-tuple of values ( struct_time ) Time starts at epoch (for UNIX: 1.1.1970, 00:00:00) Popular functions: Seconds since epoch (as a float): Convert time in seconds (float) to time.time() struct_time : time.localtime([seconds]) If seconds is None the actual time is returned. Convert Convert struct_time in seconds (float): time.mktime(t) struct_time in formatted string: time.strftime(format[, t ] ) Suspend execution of current thread for secs seconds: time.sleep(secs)
  • 24. 3/4/2023 Date and Time: datetime Date and time objects: d1 = dat et i m e. dat e ( 2008, 3, 21) d2 = dat et i m e. dat e ( 2008, 6, 22) dt = dat et i m e. dat et i m e ( 2011, 8, 26, 12, 30) t = dat et i m e. t i m e ( 12, 30) Calculating with date and time: pr i nt ( d1 < d2) d e l t a = d2 - d1 pr i nt ( del t a . days ) pr i nt ( d2 + dat et i m e. t i m edel t a( days =44) ) Operations on Path Names: os.path Paths: abspath(path) , basename(path) , normpath(path) , realpath(path) Construct paths: join(path1[, path2[, . . . ] ] ) Split paths: split(path) , splitext(path) File information: isfile(path) , isdir(path) , islink(path) , getsize(path) , .. . Expand home directory: expanduser(path) Expand environment variables: expandvars(path) >>> os . pat h. j oi n( " s pam" , " eggs " , " ham. t xt " ) ’ spam/ eggs/ ham. t x t ’ >>> o s . path . s p l i t e x t ( " spam/ e g g s . py") ( ’ s pam/ eggs ’ , ’ . py’ ) >>> os . pat h. expandus er ( " ~/ s pam" ) ’ /hom e/ r br eu/ s pam’ >>> os . pat h. expandvar s ( " /m ydi r / $TEST" ) ’ / mydir/ t e s t . py’ Files and Directories: os Working directory: getcwd() , chdir(path) Changing file permissions: chmod(path, mode) Changing owner: chown(path, uid, gid) Creating directories: mkdir(path[, mode]) , makedirs(path[, mode]) Removing files: remove(path) , removedirs(path) Renaming files: rename(src, dst) , renames(old, new) List of files in a directory: listdir(path) f or m yf i l e i n os . l i s t di r ( " m ydi r " ) : os . c hm od( os . pat h. j oi n( " m ydi r " , m yf i l e) , os . pat h. s t at . S_ I RGRP) Files and Directories: shutil Higher level operations on files and directories. Mighty wrapper functions for os module. Copying files: copyfile(src, dst) , copy(src, dst) Recursive copy: copytree(src, dst[, symlinks]) Recursive removal: rmtree(path[, ignore_errors[, onerror]]) Recursive move: move(src, dst) s hut i l . c opyt r ee( " s pam/ eggs " , " . . / beans " , s ym l i nks =Tr ue)
  • 25. 3/4/2023 Directory Listing: glob glob(path) List of files in a directory with Unix-like extension of wildcards: >>> gl ob. gl ob( " pyt hon/[ a- c ] * . py" ) [ ’ pyt hon/ c onf i t es t . py’ , ’ pyt hon/ bas i c s . py’ , ’ pyt hon/ c ur s es _ t es t 2. py’ , ’ pyt hon/ c ur s es _ keys . py’ , ’ pyt hon/c m p. py’ , ’ pyt hon/ but t on_ t es t . py’ , ’ pyt hon/ ar gum ent . py’ , ’ pyt hon/ c ur s es _ t es t . py’ ] Run Processes: subprocess Simple execution of a program: p = s ubpr oc es s . Popen( [ " l s " , " - l " , " m ydi r " ] ) r et ur nc ode = p. wai t ( ) # wait for p to end Access to the program’s output: p = Popen ( [ " l s " ] , stdout=PIPE , std err= STDOUT) p . wait ( ) out put = p. s t dout . r ead( ) Pipes between processes ( l s - l | grep txt ) p1 = Popen ( [ " l s " , " - l " ] , stdout= PIPE ) p2 = Popen ( [ " grep " , " t x t " ] , std in =p1. s tdo ut) Access to Command Line Parameters: argparse (1) Python program with standard command line option handling: $ . / ar gum ent Par s er . py - h us age : ar gum ent Par s e . py [ - h] - f FI LENAM E [ - v] Example how to use argparse o pti o n al arguments: - h, - - hel p - f FI LENAM E, - - f i l e FI LENAM E - v, - - ver bos i t y show t h i s help message and e x i t output f i l e i nc rease output verb o si ty $ pyt hon3 ar gum ent Par s e. py - f newf i l e. t xt - v new fi l e . t x t True Access to Command Line Parameters: argparse (2) Simple list of parameters: → sys.argv More convenient for handling several options: argparse optparse Deprecated module (since Python 2.7/3.2) argumentParse.py par s er = ar gpar s e. Ar gum ent Par s er ( d e s c r i p t i o n = ’ Example howto use argparse ’ ) p a r s e r . a d d _ a r g u me nt (" -f " , " - - f i l e " , des t =" f i l enam e" , def aul t =" out . t xt " , hel p=" out put f i l e " ) p a r s e r . a d d _ a r g u m e n t ( " - v ", " - - verb o si ty " , ac t i on=" s t or e_ t r ue" , hel p=" i nc r eas e out put ver bos i t y" ) ar gs = par s er . par s e_ ar gs ( ) pr i nt ( ar gs . f i l enam e) pr i nt ( ar gs . ver bos i t y)
  • 26. 3/4/2023 CSV Files: csv (1) CSV: Comma Seperated Values Data tables in ASCII format Import/Export by MS Excel Ⓧ R Columns are delimited by a predefined character (most often comma) f = open( " t es t . c s v" , " r " ) r eader = c s v. r eader ( f ) fo r row in r e a d e r : f or i t em i n r ow: pr i nt ( i t em) f . c l os e ( ) f = open( out f i l e , " w" ) wr i t er = c s v. wr i t er ( f ) wr i t er . wr i t er ow( [ 1, 2, 3, 4] ) CSV Files: csv (2) Handling different kinds of formats (dialects): csv . reader( c s v f i l e , d i a l e c t = ’ exc el ’ ) # Default c s v. wr i t er ( c s vf i l e , di al ec t =’ exc el _ t ab’ ) Specifying individual format parameters: c s v. r eader ( c s vf i l e , del i m i t er =" ; " ) Further format parameters: lineterminator , quotechar , skipinitialspace , .. . sqlite3 Lightweight Database: (1) Database in a file or in memory; in Python’s stdlib since 2.5. c onn = s ql i t e3. c onnec t ( " bl a . db" ) c = c onn. c ur s or ( ) TEXT)""") c . exec ut e( """CREATE TABLE Friends (firstname TEXT, lastname c . exec ut e( """INSERT INTO Friends VALUES("Jane", "Doe")""") c onn. c om m i t ( ) c . exec ut e( """SELECT * FROM Friends""") fo r row in c : pr i nt ( r ow) c . c l os e ( ) ; c onn. c l os e ( ) sqlite3 Lightweight Database: (2) String formatting is insecure since it allows injection of arbitrary SQL code! # Never do this! s ym bol = " J ane" c . execute ( " . . . WHERE fi rs tnam e =’ { 0 } ’ " . format( symbol ) )
  • 27. 3/4/2023 sqlite3 Lightweight Database: (3) Instead: Use the placeholder the database API provides: c . exec ut e( " . . . W HERE nam e = ? " , s ym bol ) f r i e n d s = ( ( " J a n i s " , " J o p l i n " ) , ( " Bob" , " Dylan " ) ) fo r item in f r i e n d s : c . exec ut e( """INSERT INTO Friends VALUES (?,?)""", i t em) cx_Oracle ⇒ Python module to access Oracle database Web page: http://cx-oracle.sourceforge.net/ XML based Client-Server Communication: xmlrpc (1) XML-RPC: Remote Procedure Call uses XML via HTTP Independent of platform and programming language For the client use xmlrpc.client i m por t xm l r pc . c l i ent s = xml rp c . c l i e n t . S e r v e r ( " h ttp :// l o c a l h o s t :8000 " ) # print list of available methods pr i nt ( s . s ys t em . l i s t M et hods ( ) ) # use methods pr i nt ( s . add( 2, 3) ) pr i nt ( s . s ub( 5, 2) ) Automatic type conversion for the standard data types: boolean, integer, floats, strings, tuple, list, dictionarys (strings as keys), . .. XML based Client-Server Communication: xmlrpc (2) For the server use xmlrpc.server from xml rp c . s erver import Simple XMLRPCServer offered by the server: # methods which are to be c l as s M yFunc s : def add( s el f , x , y) : return x + y def s ub( s el f , x , y) : return x - y # create and start the server: server = Simple XMLRPCServer ( ( " l o c a l h o s t " , 8000)) s e r v e r . r e g i s t e r _ i n s t a n c e ( My Funcs ( ) ) s e r v e r . s e r v e _ f o r e v e r ( ) More Modules readline : Functionality for command line history and auto-completion tempfile : Generate temporary files and directories numpy: Numeric Python package N-dimensional arrays Supports linear algebra, Fourier transform and random number capabilities Part of the SciPy stack mathplotlib : 2D plotting library, part of the SciPy stack ...
  • 28. 3/4/2023 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Conditional Expressions A conditional assignment as i f value <0: s = " negat i ve" el s e : s = " pos i t i ve" can be realized in abbreviated form s = " negat i ve" i f val ue <0 el s e " pos i t i ve" List Comprehension Allows sequences to be build by sequences. Instead of using for : a = [ ] f or i i n r ange ( 10) : a. append( i * * 2) List comprehension can be used: a = [ i * * 2 f or i i n r ange ( 10) ] Conditional values in list comprehension: a = [ i * * 2 f or i i n r ange ( 10) i f i ! = 4] Since Python 2.7: set and dictionary comprehension s = { i * 2 f or i i n r ange ( 3) } d = { i : i * 2 f or i i n r ange ( 3) } Dynamic Attributes Remember: Attributes can be added to python objects at runtime: c l as s Em pt y: pass a = Em pt y( ) a. s pam = 42 a. eggs = 17 Also the attributes can be deleted at runtime: del ( a. s pam)
  • 29. 3/4/2023 getattr , setattr , hasattr Attributes of an object can be accessed by name (string): import math f = get at t r ( m at h, " s i n " ) pr i nt ( f ( x) ) # sin(x) a = Em pt y( ) s et at t r ( a, " s pam" , 42) pr i nt ( a. s pam) Useful if depending on user or data input. Check if attribute is defined: i f not has at t r ( a, " s pam" ) : s et at t r ( a, " s pam" , 42) pr i nt ( a. s pam) Anonymous Function Lambda Also known as lambda expression and lambda form >>> f = lambda x , y : x + y >>> f ( 2, 3) 5 >>> ( l am bda x: x * * 2) ( 3) 9 Useful if only a simple function is required as an parameter in a function call: >>> f r i ends = [ " al i c e " , " Bob" ] >>> f r i ends . s or t ( ) >>> f r i e n d s [ ’ Bob’ , ’ al i c e ’ ] >>> f r i ends . s or t ( key = l am bda a: a. upper ( ) ) >>> f r i e n d s [ ’ al i c e ’ , ’ Bob’ ] Functions Parameters from Lists and Dictionaries def s pam( a, b, c , d) : p r i n t ( a , b , c , d) Positional parameters can be created by lists: >>> ar gs = [ 3, 6, 2, 3] >>> s pam( * ar gs ) 3 6 2 3 Keyword parameters can be created by dictionaries: >>> kwar gs = { " c " : 5, " a" : 2, " b" : 4, " d" : 1} >>> s pam( * * kwar gs ) 2 4 5 1 Variable Number of Parameters in Functions def s pam( * ar gs , * * kwar gs ) : fo r i in a r g s : pr i nt ( i ) fo r i in kwargs: pr i nt ( i , kwar gs [ i ] ) >>> s pam( 1, 2, c =3, d=4) 1 2 c. 3 d. 4
  • 30. 3/4/2023 Global and Static Variables in Functions global links the given name to a global variabile Static variable can be defined as an attribute of the function def m yf unc ( ) : g l o b al max_size i f not has at t r ( m yf unc , " _ c ount er " ) : m yf unc . _ c ount er = 0 # it doesn’t exist yet, # so initialize it m yf unc . _ c ount er += 1 pr i nt ( " { 0: d} . c al l " . f or m at ( m yf unc . _ c ount er ) ) pr i nt ( " m ax s i z e i s { 0: d} " . f or m at ( m ax_ s i z e ) ) . . . >>> max_size = 222 >>> m yf unc ( ) 1 . c a l l max s i z e i s 222 Map Apply specific function on each list element: >>> l i = [ 1, 4, 81, 9] >>> m apl i = m ap( m at h. sqr t , l i ) >>> mapli <m ap obj ec t at 0x7f 5748240b90 > >>> l i s t ( m apl i ) [ 1. 0, 2. 0, 9. 0, 3. 0] >>> l i s t ( m ap( l am bda x: x * 2, l i ) ) [2 , 8, 162, 18] Functions with more than one parameter requires an additional list per parameter: >>> l i s t ( m ap( m at h. pow, l i , [ 1, 2, 3, 4] ) ) [ 1. 0, 16. 0, 531441. 0, 6561. 0] Filter Similar to map, but the result is a f i l t e r object, which contains only list elements, where the function returns True . filter_example.py l i = [ 1, 2, 3, 4, 5, 6, 7, 8, 9] l i Odd = f i l t er ( l am bda x: x % 2, l i ) p r i n t ( " l i = " , l i ) pr i nt ( " l i Odd =" , l i Odd) p r i n t ( " l i s t ( liOdd ) = " , l i s t ( liOdd ) ) $ pyt hon3 f i l t er _ exam pl e. py l i = [ 1, 2, 3, 4, 5, 6, 7, 8, 9] liOdd = < f i l t e r o b j e c t at 0x7fe4 ccdcb 7c0 > l i s t ( l i Odd) = [ 1, 3, 5, 7, 9] $ Zip Join multiple sequences to one list of tuples: Useful when iterating on multiple sequences in parallel >>> l i s t ( z i p( " ABC" , " 123" ) ) [ ( ’ A’ , ’ 1’ ) , ( ’ B’ , ’ 2’ ) , ( ’ C’ , ’ 3’ ) ] >>> l i s t ( z i p( [ 1, 2, 3] , " ABC" , " XYZ" ) ) [ ( 1, ’ A’ , ’ X’ ) , ( 2, ’ B’ , ’ Y’ ) , ( 3, ’ C’ , ’ Z’ ) ] Example: How to create a dictionary by two sequences >>> di c t ( z i p( ( " appl e" , " peac h" ) , ( 2, 0) ) ) { ’ appl e ’ : 2, ’ peac h’ : 0}
  • 31. 3/4/2023 Iterators (1) for is applied on an object? What happens, if fo r i in o b j : pass iter The method for obj is called, return an iterator. On each loop cycle the iterator. next () method will be called. StopIteration The exception is raised when there are no more elements. Advantage: Memory efficient (access time) Iterators (2) c l as s Rever s e: def _ _ i ni t _ _ ( sel f , dat a ) : s el f . dat a = dat a s el f . i ndex = l en( dat a ) def _ _ i t er _ _ ( s el f ) : return s e l f def _ _ next _ _ ( s el f ) : i f s el f . i ndex == 0: s el f . i ndex = l en( s el f . dat a ) r ai s e St opI t er at i on s el f . i ndex = s el f . i ndex - 1 r et ur n s el f . dat a [ s el f . i ndex ] >>> f or c har i n Rever s e( " s pam" ) : pr i nt ( c har , end=" " ) . . . . . . m a p s Generators Simple way to create iterators: yield Methods uses the statement ⇒ breaks at this point, returns element and continues there on the next iterator. next () call. def r ever s e( dat a ) : f or el em ent i n dat a [ : : - 1] : y i e l d element >>> f or c har i n r ever s e( " s pam" ) : pr i nt ( c har , end=" " ) . . . . . . m a p s Generator Expressions Similar to the list comprehension an iterator can be created using a generator expression: >>> dat a = " s pam" >>> f or c i n ( el em f or el em i n dat a [ : : - 1] ) : pr i nt ( c , end=" " ) . . . . . . m a p s
  • 32. 3/4/2023 Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook IPython (I) Enhanced interactive Python shell Numbered input/output prompts Object introspection System shell access IPython (II) Tab-completion Command history retrieval across session User-extensible ‘magic’ commands %timeit ⇒Time execution of a Python statement or expression using the timeit module %cd ⇒Change the current working directory %edit ⇒Bring up an editor and execute the resulting code %run ⇒Run the named file inside IPython as a program ⇒more ’magic’ commands ⇒IPython documentation PIP Installs Python/Packages (I) Command pip A tool for installing Python packages Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include by default Installing Packages pip $ pi p3 i ns t al l Som ePac kage $ pi p3 i ns t al l - - us er Som ePac kage #us er i ns t al l Uninstall Packages $ pi p3 uni ns t al l Som ePac kage
  • 33. 3/4/2023 PIP Installs Python/Packages (II) Listing Packages $ pip3 l i s t doc ut i l s ( 0. 9. 1) J i nj a2 ( 2. 10) Pygm ent s ( 2. 3. 1) Sphi nx ( 1. 1. 2) $ pi p3 l i s t - - out dat ed doc ut i l s ( Cur r ent : 0. 9. 1 L a t e s t : 0. 14) Sphi nx ( Cur r ent : 1. 1. 2 Lat es t : 2. 10) Searching for Packages $ pi p3 s ear c h " quer y" ⇒pip documentation pyenv - Simple Python Version Management (I) Easily switch between multiple versions of Python Doesn’t depend on Python itself Inserts directory of shims4 at the front of your Easy Installation: PATH $ g i t clone http s :// github . com/ yyuu / pyenv. g i t ~/. pyenv $ ec ho ’ expor t PYENV_ ROOT=" $ HOM E/. pyenv" ’ >> ~/. bas hr c $ echo ’ export PATH=" $ PYENV_ROOT/bin : $ PATH" ’ >> ~/. bashrc $ ec ho ’ eval " $ ( pyenv i ni t - ) " ’ >> ~/. bas hr c ⇒pyenv repository 4 kind of infrastructure to redirect system/function calls metaphor: A shim is a piece of wood or metal to make two things fit together pyenv - Simple Python Version Management (II) Install Python versions into $PYENV_ROOT/versions $ pyenv i ns t al l - - l i s t $ pyenv i n s t a l l 3 . 7 . 4 # a v a i l a b l e Python vers io ns #i n s t a l l Python 3 . 7 . 4 Change the Python version $ pyenv g l o b a l 3 . 7 . 4 $ pyenv l o c a l 3 . 7 . 4 $ pyenv s h e l l 3 . 7 . 4 # g l o b a l Python # per - pr oj ec t Pyt hon # s hel l - s pec i f i c Pyt hon List all installed Python versions (asterisk shows the active) $ pyenv versi o n s system 2. 7. 16 * 3 . 7 . 4 ( set by PYENV_VERSION environment v a r i a b l e ) Virtual Environments Allow Python packages to be installed in an isolated location Use cases Two applications need different versions of a library Install an application and leave it be Can’t install packages into the global site-packages directory Virtual environments have their own installation directories Virtual environments don’t share libraries with other virtual environments Available implementations: virtualenv (Python 2 and Python 3) venv (Python 3.3 and later)
  • 34. 3/4/2023 venv Create virtual environment $ pyt hon3 - m venv / pat h/t o/env Activate $ s our c e / pat h/t o/env/bi n/ ac t i vat e Deactivate $ d e a c t i v a t e ⇒venv documentation Pylint (I) pylint li n t is the implementation for python code Checks for errors in Python code Tries to enforce a coding standard Looks for bad code smells Displays classified messages under various categories such as errors and warnings Displays statistics about the number of warnings and errors found in different files Pylint (II) The code is given an overall mark $ pyt hon3 - m pyl i nt exam pl e. py . . . G l o bal evaluat io n - - - - - - - - - - - - - - - - - Your c ode has been r at ed at 10. 00/10 ( pr evi ous r un: 9. 47/10, +0. 53) ⇒Pylint documentation Software testing Part of quality management Point out the defects and errors that were made during the development phases It always ensures the users or customers satisfaction and reliability of the application The cost of fixing the bug is larger if testing is not done ⇒testing saves time Python testing tools pytest unittest . ..
  • 35. 3/4/2023 pytest Easy to get started test_ prefixed test functions or methods are test items assert Asserting with the statement pytest will run all files in the current directory and its subdirectories of the form test_*.py or *_test.py Usage: $ pyt hon3 - m pyt es t . . . $ pyt hon3 - m pyt es t exam pl e . py . . . ⇒pytest documentation pytest Example: Check Function Return Value example1_test.py def i nc r ( x ) : return x + 11 def t es t _ i nc r ( ) : as s er t i nc r ( 3) == 4 $ python3 -m p yt est -v example1_ t e s t . py . . . _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ t e s t _ i n c r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ > E E def t es t _ i nc r ( ) : as s er t i nc r ( 3) == 4 a s s e r t 14 == 4 + wher e 14 = i nc r ( 3) exam pl e1_ t es t . py : 5: As s er t i onEr r or ============= 1 f a i l e d in 0.00 seconds ============= pytest Example: Check for expected Exception import pytest def f ( ) : r ai s e Sys t em Exi t ( 1) def t es t _ er r or ( ) : wi t h pyt es t . r ai s es ( Sys t em Exi t ) : #passes f ( ) Slide 146 pytest Example: Check for expected Exception import pytes t def f ( ) : r ai s e Sys t em Exi t ( 1) def t es t _ er r or ( ) : wi t h pyt es t . r ai s es ( Sys t em Exi t ) : #passes f ( ) pytest Example: Comparing Two Data Object def t e s t _ l i s t _ c o m p a r i s o n ( ) : l i s t 1 = [ 1, 3, 0, 8] l i s t 2 = [ 1, 3, 3, 8] a s s e r t l i s t 1 == l i s t 2 #fails Slide 146
  • 36. 3/4/2023 pytest Example: Parameterize Test Function def i nc r ( x ) : return x + 1 @ p y t e s t . mark. parametrize ( " t e s t _ i n p u t , expected " , [ (1 , 2 ) , ( 2, 3) , ( 3, 4) , ] ) def t es t _ i nc r ( t es t _ i nput , expec t ed) : a s s e r t i n c r ( t e s t _ i n p u t ) == expected Table of Contents Introduction Data Types I Control Statements Functions Input/Output Errors and Exceptions Data Types II Object Oriented Programming Modules and Packages Advanced Techniques Tools Regular Expressions (optional) Summary and Outlook Regular Expressions – Introduction Regular expression (RegExp): Formal language for pattern matching in strings Motivation: Analyze various text files: Log files Data files (e.g. experimental data, system configuration, . . .) Command output . .. Python module: import re >>> r e. f i ndal l ( r " a. c " , " abc aac aa abb a c " ) [ ’ a b c ’ , ’ aac ’ , ’ a c ’ ] Remember: r " . . . " ⇒ raw string (escape sequences are not interpreted) Regular Expressions – Character Classes Class/set of possible characters: [ ! ? : . , ; a - z ] ˆ at the beginning negates the class. e.g.: [ˆaeiou] ⇒ all characters besides the vocals Character class in pattern tests for one character The . represents any (one) character Predefined character classes: name whitespace word character d i g i t character [ t n r f ] Acr . negated s S w W d D [ a−zA−Z_0−9] [0−9] >>> r e. f i ndal l ( r " s ds " , " 1 22 4 22 1 a b c " ) [ ’ 4 ’ , ’ 1 ’ ] >>> r e. f i ndal l ( r " [ ^aei ou] " , " Pyt hon Kur s " ) [ ’ P ’ , ’ y ’ , ’ t ’ , ’ h ’ , ’ n ’ , ’ ’ , ’ K ’ , ’ r ’ , ’ s ’ ]
  • 37. 3/4/2023 Regular Expressions – Quantifiers Quantifier can be defined in ranges (min, max): d{5,7} matches sequences of 5-7 digits Acronym: {1} {0 ,} {0 ,1} {1 ,} one−time occurrence Default none to multiple occurrences ∗ none or one−time occurrence ? + at least one−time occurrence >>> r e . f i n d a l l ( r " [ ab ] {1 , 2 } " , " a aa ab ba bb b ") [ ’ a’ , ’ aa ’ , ’ ab’ , ’ ba ’ , ’ bb’ , ’ b’ ] >>> r e . f i n d a l l ( r" d + " , " 1 . Python Kurs 2012" ) [ ’ 1’ , ’ 2012’ ] Regular Expressions – Anchors Anchors define special restrictions to the pattern matching: b B ^ $ word boundary , switch between w and W negate b s t ar t of the s t ri ng end of the s t r i ng >>> r e . f i n d a l l ( r " ^d + " , " 1 . Python Course 2015" ) [ ’ 1’ ] Look-around anchors (context): Lookahead ab(?=c ) ab ( ?! c ) Lookbehind (?<=c )ab (? <!c )ab matches "ab" i f i t ’ s part of "abc " matches "ab" i f not followed by a " c " matches "ab" i f i t ’ s part of "cab " matches "ab" i f not behind a " c " Regular Expression – Rules for Pattern Matching Pattern analysis will start at the beginning of the string. If pattern matches, analysis will continue as long as the pattern is still matching (greedy). Pattern matching behavior can be changed to non-greedy by using the "?" behind the quantifier. ⇒ the pattern analysis stops at the first (minimal) matching >>> r e . f i n d a l l ( r " Py. * o n " , " Python . . . Python " ) [ ’ Python . . . Python ’ ] >>> r e . f i n d a l l ( r " Py. * ? o n " , " Python . . . Python " ) [ ’ Python ’ , ’ Python ’ ] Regular Expressions – Groups () brackets in a pattern create a group Group name is numbered serially (starting with 1) The first 99 groups ( 1 - 99 ) can be referenced in the same pattern Patterns can be combined with logical or ( | ) inside a group >>> r e . f i n d a l l ( r " ( w+) 1" , " Py Py abc Test T e s t " ) [ ’ Py’ , ’ Test ’ ] >>> >>> r e . f i n d a l l ( r " ( [ A- Za - z ] + | d + ) " , " uid =2765( zdv124) " ) [ ’ ui d’ , ’ 2765’ , ’ z dv’ , ’ 124’ ] >>> >>> r e. f i ndal l ( r " ( [ . * ? ] | <. * ? >) " , " [ hi ] s <b>s d<hal >" ) [ ’ [ h i ] ’ , ’ < b > ’ , ’ <hal > ’ ]
  • 38. 3/4/2023 Regular Expressions – Group Usage re.* Some methods return a re.MatchObject ⇒ contain captured groups re_groups.py t e x t = " adm06: x :706 :1000 : S t . Graf : / home/ adm06: / bin / bash " grp = r e . match ( r " ^( [ a - z0 -9 ] + ) : x : [ 0 -9 ] + : [ 0 -9 ] + : ( . + ) : . + : . + $ " , t e x t ) i f ( gr p) : pr i nt ( " f ound: " , gr p. gr oups ( ) ) pr i nt ( " us er I D=" , gr p. gr oup( 1) ) pr i nt ( " nam e =" , gr p. gr oup( 2) ) $ pyt hon3 r e_ gr oups . py f ound: ( ’ adm 06’ , ’ St . Gr af ’ ) user ID= adm06 nam e = St . Gr af Regular Expressions – Matching Flags Special flags can change behavior of the pattern matching r e . I : Case insensitive pattern matching re.M : ˆ or. $ will match at beginning/end of each line (not only at the beginning/end of string) re.S : . also matches newline ( n ) >>> r e. f i ndal l ( " ^abc " , " Abc nabc " ) [ ] >>> r e. f i ndal l ( " ^abc " , " Abc nabc " , r e. I ) [ ’ A b c ’ ] >>> r e. f i ndal l ( " ^abc " , " Abc nabc " , r e. I | r e. M) [ ’ A b c ’ , ’ abc ’ ] >>> r e. f i ndal l ( " ^Abc . " , " Abc nabc " ) [ ] >>> r e. f i ndal l ( " ^Abc . " , " Abc nabc " , r e. S) [ ’ Abcn ’ ] Regular Expressions – Methods (I) findall: Simple pattern matching ⇒ list of strings (hits) >>> r e. f i ndal l ( r " [ . * ? ] " , " a[ bc ] g[ hal ] def " ) [ ’ [ b c ] ’ , ’ [ h a l ] ’ ] sub: Query replace ⇒ new (replaced) string >>> r e. s ub( r " [ . * ? ] " , " ! " , " a[ bc ] g[ hal ] def " ) ’ a ! g ! d e f ’ search: Find first match of the pattern re.MatchObject ⇒ returns or None i f r e . search ( r " [ . * ? ] " , " a[ b c ] g[ h a l ] d e f " ) : pr i nt ( " pat t er n m at c hed! " ) Regular Expressions – Methods (II) match: Starts pattern matching at beginning of the string re.MatchObject ⇒ returns or None t e x t = " adm06: x :706 :1000 : S t . Graf : / home/ adm06: / bin / bash " grp = r e . match ( " ( [ a - z0 -9 ] + ) : x : [ 0 -9 ] + : [ 0 -9 ] + : ( . + ) : . + : . + $ " , t e x t ) compile: Regular expressions can be pre-compiled ⇒ gain performance on reusing these RegExp multiple times (e.g. in loops) >>> pat t er n = r e. c om pi l e( r " [ . * ? ] " ) >>> pat t er n. f i ndal l ( " a[ bc ] g[ hal ] def " ) [ ’ [ bc ] ’ , ’ [ hal ] ’ ]