Python
Python
Script Programming
March 2018 St. Graf, S. Linner, M. Lischewski Forschungszentrum Jülich
# This is a commentary
print ( " Hello world ! " )
$ python3 hello_world . py
Hello world !
$
hello_user.py
# !/ usr / bin / env python3
$ ./ hello_user . py
What ’ s your name ? Rebecca
Hello Rebecca
$
1
James Whitcomb Riley
Python 2 Python 3
shebang1 #!/usr/bin/python #!/usr/bin/python3
IDLE cmd1 idle idle3
print cmd (syntax) print print()
input cmd (syntax) raw_input() input()
unicode u"..." all strings
integer type int/long int (infinite)
... hints in each chapter
⇒http://docs.python.org/3/whatsnew/3.0.html
1
linux specific
a = 1
c = 1.0
c = 1 e0
d = 1 + 0j
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.
>>> s1 = [1, 2, 3, 4]
1
>>>
>>>
s2 = s1
s2[1] = 17
s1 2
>>> s1
3
[1, 17, 3, 4] s2
>>> s2 4
[1, 17, 3, 4]
>>> s1 = [1, 2, 3, 4]
1
>>>
>>>
s2 = s1
s2[1] = 17
s1 17
>>> s1
3
[1, 17, 3, 4] s2
>>> s2 4
[1, 17, 3, 4]
if a == 3:
print ( " Aha ! " )
i = 0
while i < 10:
i += 1
def add (a , b ):
""" Returns the sum of a and b . """
mysum = a + b
return mysum
add (a , b )
Returns the sum of a and b .
a = hello_world ()
print ( a )
$ python3 my_program . py
Hello World
None
ret = foo ()
(x , y ) = foo ()
$ python3 plot_lines . py
0 1 2 3 4
1 0 -1 -2 -3
printContact ( name = " Peter Pan " , location = " Neverland " , age =10)
$ python3 displayPerson . py
Person : Peter Pan
Age : 10 years
Address : Neverland
Functions are objects and as such can be assigned and passed on:
>>> a = float
>>> a (22)
22.0
Keyword arguments :
real -- the real part ( default 0.0)
imag -- the imaginary part ( default 0.0)
"""
...
More information for standard modules and how to create your own module see chapter
Modules and Packages on slide 90
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)
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.
>>> name = " Martin "
>>> age = 50
>>> f " My name is { name } and my age next year is { age +1} "
’ My name is Martin and my age next year is 51 ’
>>> value = 12.345
>>> f " value ={ value :5.2 f } "
’ value =12.35 ’
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.
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+
for line in file1 :
print ( line )
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()
After finishing the with block the file object is closed, even if an exception occurred
inside the block.
$ python3 add . py
File " add . py " , line 2
def add (a , b )
^
SyntaxError : invalid syntax
$ python3 test . py
I ’ m running ...
Traceback ( most recent call last ):
File " test . py " , line 3 , in < module >
math . foo ()
AttributeError : module ’ math ’ has no
attribute ’foo ’
except block is executed when the code in the try block throws an according
exception
Afterwards, the program continues normally
Unhandled exceptions force the program to exit.
Handling different kinds of exceptions:
except ( ValueError , TypeError , NameError ):
try :
f = open ( " spam " )
except IOError :
print ( " Cannot open file " )
else :
print ( f . read ())
f . close ()
finally :
print ( " End of try . " )
$ python3 spam_open . py
2 spam No such file or directory
[ Errno 2] No such file or directory : ’ spam ’
draw()
rectangle()
line() Exception!
Raising exceptions:
def gauss_solver ( matrix ):
# Important code
raise ValueError ( " Singular matrix " )
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!
def square ( x ):
return x ** 2
...
try :
result = square ( value )
except TypeError :
print ( " ’{0} ’: Invalid type " . format ( value ))
Some objects offer context management 2 , which provides a more convenient way to
write try ... finally blocks:
with open ( " test . txt " ) as f :
for line in f :
print ( line )
After the with block the file object is guaranteed to be closed properly, no matter what
exceptions occurred within the block.
2
Class method __enter__(self) will be executed at the beginning and class method __exit__(...)
at the end of the context
my_point.py
class Point :
pass
p = Point ()
p . x = 2.0
p . y = 3.3
my_point.py
class Point :
def __init__ ( self , x , y ):
self . x = x
self . y = y
>>> print ( p )
(2.0 , 3.0)
Numeric operators:
+ : __add__(self, other)
- : __sub__(self, other)
* : __mul__(self, other)
...
@classmethod
def cmethod ( cls ):
print ( cls . spam )
@staticmethod
def smethod ():
print ( " Blah blah . " )
Spam . cmethod ()
Spam . smethod ()
s = Spam ()
s . cmethod ()
s . smethod ()
There are often classes that are very similar to each other.
Inheritance allows for:
Hierarchical class structure (is-a-relationship)
Reusing of similar code
class Phone :
def call ( self ):
pass
h = SmartPhone ()
h . call () # inherited from MobilePhone
h . take_photo () # inherited from Camera
class Spam :
__eggs = 3
_bacon = 1
beans = 5
Getter and setter can be added later without changing the API
Access to _value still possible
import math as m
s = m . sin ( m . pi )
def add (a , b ):
""" Add a and b . """
return a + b
If instructions should only be executed when running as a script, not importing it:
my_module.py
def add (a , b ):
return a + b
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)
shutil . copytree ( " spam / eggs " , " ../ beans " ,
symlinks = True )
optional arguments :
-h , -- help show this help message and exit
-f FILENAME , -- file FILENAME output file
-v , -- verbosity increase output verbosity
c . close ();
conn . close ()
friends = (( " Janis " , " Joplin " ) , ( " Bob " , " Dylan " ))
for item in friends :
c . execute ( """ INSERT INTO Friends
VALUES (? ,?) """ , item )
Automatic type conversion for the standard data types: boolean, integer, floats, strings,
tuple, list, dictionarys (strings as keys), . . .
A conditional assignment as
if value <0:
s = " negative "
else :
s = " positive "
a = Empty ()
a . spam = 42
a . eggs = 17
a = Empty ()
setattr (a , " spam " , 42)
print ( a . spam )
def spam (a , b , c , d ):
print (a , b , c , d )
Functions with more then one parameter requires an additional list per parameter:
>>> list ( map ( math . pow , li , [1 , 2 , 3 , 4]))
[1.0 , 16.0 , 531441.0 , 6561.0]
Similar to map , but the result is a new list with the list elements, where the functions
returns True .
filter_example.py
li = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
liFiltered = filter ( lambda x : x % 2 , li )
print ( " li = " , li )
print ( " liFiltered = " , list ( liFiltered ))
$ python3 filter_example . py
li = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
liFiltered = [1 , 3 , 5 , 7 , 9]
$
Similar to the list comprehension an iterator can be created using a generator expression:
>>> data = " spam "
>>> for c in ( elem for elem in data [:: -1]):
... print (c , end = " " )
...
m a p s
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
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 pip
by default
Installing Packages
$ pip3 install SomePackage
$ pip3 install -- user SomePackage # user install
Uninstall Packages
$ pip3 uninstall SomePackage
Listing Packages
$ pip3 list
docutils (0.9.1)
Jinja2 (2.6)
Pygments (1.5)
Sphinx (1.1.2)
$ pip3 list -- outdated
docutils ( Current : 0.9.1 Latest : 0.10)
Sphinx ( Current : 1.1.2 Latest : 1.1.3)
⇒pip documentation
⇒pyenv repository
3
kind of infrastructure to redirect system/function calls
metaphor: A shim is a piece of wood or metal to make two things fit together
Activate
$ source / path / to / env / bin / activate
Deactivate
$ deactivate
⇒Virtualenv documentation
PEP8 is a style guide for Python and gives coding conventions for:
Code layout / String Quotes / Comments / ...
pep8 is a tool to check your Python code against some of the style conventions in
PEP 8.
Usage
$ python3 -m pep8 example . py
example . py :6:6: E225 missing whitespace around operator
⇒PEP8 documentation
...
Global evaluation
-----------------
Your code has been rated at 10.00/10
( previous run : 9.47/10 , +0.53)
⇒Pylint documentation
⇒pytest documentation
def f ():
raise SystemExit (1)
def f ():
raise SystemExit (1)
def incr ( x ):
return x + 1
Remember:
r"..." ⇒ raw string (escape sequences are not interpreted)
$ python3 re_groups . py
found : ( ’ adm06 ’ , ’ St . Graf ’)
user ID = adm06
name = St . Graf
We have learned:
Multiple data types (e.g. „high level“)
Common statements
Declaration and usage of functions
Modules and packages
Errors and Exceptions, exception handling
Object oriented programming
Some of the often used standard modules
Popular tools for Python developers
Alternative to MatLab:
Matrix algebra, numeric functions, plotting, ...