Excercise 00 - Python Tutorial

Intelligent Software Systems - Summer Term 2019
by André Karge (andre.karge@uni-weimar.de)

xkcd

https://xkcd.com/353/

What is Python?

"Python is an interpreted high-level programming language for general-purpose programming" - wikipedia.org

Motivation & Basics

  • Uses interpreter which reads and processes instructions stored in a script
  • Python script is a text file containing Python instructions
  • Can be learned easily
  • Algorithms can be implemented fast and uncomplicated

Programming in Python

with an editor:

  • open editor of your choice
  • create a new file
  • write your python code in there
  • save the file as "my_python_script.py" on your disc
  • open a terminal and run your script with: python3 my_python_script.py

with an IDE:

  • install the python IDE of your choice (recommendation: pycharm by jetbrains)
  • create a new python project
  • write your code in a new python file in the project
  • run your script using the interpreter of the IDE

with Jupyter Notebook (for rapid prototyping - not for larger projects)

  • start a Jupyter Notebook server
  • create a new ipython notepad
  • write your code in the cells in there
  • run your cells with the "run"-button or by pressing "Ctrl+Return"

Styleguide

  • Python uses indentation to mark different scopes


    Use **whitespaces** for indentation


    Never use tabs for this!!
  • Default whitespace count: 4
  • limit lines to max. 80 characters to provide a good readability
  • use docstrings and comments!
  • name classes CamelCase
  • name functions lower_case_with_underscores
  • check out PEP8

Python Example

In [7]:
def helloworld(name): # function
    print("Hello world!") # call of print function
    print("your name is " + name)

helloworld("Chuck Norris") # call of helloworld function
Hello world!
your name is Chuck Norris
  • Python uses indentation to mark blocks of code
  • Lines with same indentation depth belong together and form a scope

Print

print() prints text on the standard output

In Python3 print("text") is a function call

In Python2 print "text" is just an instruction and is not available in Python3

In [89]:
print("Hello World") # a simple print
Hello World
In [91]:
# format the character string
print("{0} is the answer".format(42)) # inserts the value of .format into the string
print("{0} has {1} {2}, because of reasons".format("Chuck Norris", 12, "cats")) # multiple inserts
42 is the answer
Chuck Norris has 12 cats, because of reasons

Variables

Variable assignments by using the "=" operator

In [ ]:
variable = 1 # character string
In [3]:
# variable identifier cannot start with a number
1variable = 3 # throws error

Numerical Types

In [8]:
number1 = 1 # integer
print(type(number1))
number2 = 0.5 # floating point number
print(type(number2))
<class 'int'>
<class 'float'>

Operations

In [15]:
# addition
print(1 + 2)
3
In [16]:
# subtraction
print(2 - 1)
1
In [17]:
# multiplication
print(3 * 2)
6
In [26]:
# division
print(3 / 2)  # floating point division
print(3 // 2) # integer division
1.5
1
In [28]:
# power
print(2 ** 3)
print(pow(2,3))
8
8
In [30]:
# modulo
print(18 % 10)
print(28 % 10)
8
8
In [22]:
# assignment
a = 1 # integer
print(a)
b = "text" # string
print(b)
c = 1.0 # float
print()
1
text
In [19]:
# incrementation
a = 1
a += 1 # is the same as a = a + 1
print(a)
2

This works also with this operations:

In [ ]:
a -= 2
a *= 2
a /= 2
a //= 2

If Clauses

In [1]:
if 1 == 2:
    print("this is correct")
else:
    print("this is not correct")
this is not correct
In [36]:
if 1 == 1 and 2 != 1:
    print("this is also correct")
this is also correct

Logical Operators

Comparison

Operator Meaning
== equal
!= not equal
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal

Bitwise Operators

Operator Meaning
& binary AND
| binary OR
^ binary XOR
<< binary left shift
>> binary right shift
~ complement/not

Boolean Operators

Operator Meaning
and logical AND
or logical OR
not logical NOT

Strings

In [37]:
text = "This is a character string"
print(text)
print("This is another character string")
This is a character string
This is another character string
In [38]:
# Quotes indicate strings
text = "This is a string"
text = 'This is another string'
In [40]:
# You can use quotes inside strings
text = "This is a 'new' string"
print(text)
text = 'This is another "new" string'
print(text)
text = "This is \"another\" string" # escaping the quotes
print(text)
text = 'This is \'another\' string' # escaping the quotes
print(text)
This is a 'new' string
This is another "new" string
This is "another" string
This is 'another' string

Lists

Python uses an indexing starting at position 0

In [41]:
my_list = [1,2,3,4,5] # integer list
print(my_list)
[1, 2, 3, 4, 5]
In [43]:
my_list = [1,2,3,4,5]
print(my_list[0])   # first list element
print(my_list[1])   # second list element
print(my_list[-1])  # last list element
print(my_list[:3])  # first three list elements
print(my_list[1:3]) # get list elements starting at the second element end stopping before the fourth
1
2
5
[1, 2, 3]
[2, 3]
In [48]:
#append element to list
my_list = [1,2,3,4,5]
my_list.append(42) # append a 42 at the end
print(my_list)

# insert element in list a a position
my_list.insert(0,16) # insert 16 at position 0
print(my_list)

my_list.insert(3, 32) # insert 32 at position 3
print(my_list)
[1, 2, 3, 4, 5, 42]
[16, 1, 2, 3, 4, 5, 42]
[16, 1, 2, 32, 3, 4, 5, 42]
In [49]:
# remove element from list
my_list = [1,2,3,4,5]
my_list.pop() # remove last element
print(my_list)

my_list.pop(0) # remove element at position 0
print(my_list)

my_list.pop(2) # remove element at position 2
print(my_list)
[1, 2, 3, 4]
[2, 3, 4]
[2, 3]
In [54]:
# list functions
my_list = [1,2,3,4,5]
print(max(my_list)) # max gives the highest value of a list

print(min(my_list)) # min gives the lowest value of a list

print(len(my_list)) # len gives the length of a list

# checks (elements in the list have to be of same type)

print(5 in my_list) # check if an element is in a list

print(42 not in my_list) # check if an element is not in a list
5
1
5
True
True
In [57]:
# shallow copy vs deep copy
a = [1,2,3,4,5]
b = a # shallow copy
b.append(42)
print(a)
print(b)
[1, 2, 3, 4, 5, 42]
[1, 2, 3, 4, 5, 42]
In [58]:
from copy import deepcopy
a = [1,2,3,4,5]
b = deepcopy(a)
b.append(42)
print(a)
print(b)
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 42]
In [1]:
# Multidimensional List
matrix = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
print(matrix)
print()
print(matrix[0][1])  # get the the element at row 0 and column 1
print()
#print(matrix[0])  # get all elements at index 0 of all rows
#print()
print(matrix[0])     # get all elements of row 0
print(matrix[:2])    # get all row until row 2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

2

[1, 2, 3]
[[1, 2, 3], [4, 5, 6]]
[1, 2, 3]

more list information can be found at python documentation

Tuple

A tuple is an ordered immutable list of mixed types

In [69]:
# tuple is indicated with: ()
t = ("Chuck", "Norris", 42)
print(t)
('Chuck', 'Norris', 42)
In [72]:
t = ("Chuck", "Norris", 42)

# get value of a tuple element
print(t[0])

# no assignment possible
t[0] = "Peter"
Chuck
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-72-ad033e2fe5b0> in <module>()
      5 
      6 # no assignment possible
----> 7 t[0] = "Peter"

TypeError: 'tuple' object does not support item assignment
In [71]:
# tuple has to be unpacked first
t = ("Chuck", "Norris", 42)
firstname, lastname, answer = t
print(firstname)
print(lastname)
print(answer)
Chuck
Norris
42

Dictionaries

Unordered list of key - value pairs

The key has to be unique

In [75]:
d = {"cat": 5, "dog": 6, "bird": 12}
print(d)

print(d["cat"]) # get value for key "cat"

d["cat"] = 42 # set value for key "cat"
print(d)
{'cat': 5, 'dog': 6, 'bird': 12}
5
{'cat': 42, 'dog': 6, 'bird': 12}
In [78]:
# sorting dictionary by key
d = {"cat": 5, "dog": 6, "bird": 12}
print(d)
print(sorted(d))
{'cat': 5, 'dog': 6, 'bird': 12}
['bird', 'cat', 'dog']

more dictionary information can be found at python documentation

Loops

In [15]:
# for loop over list elements
my_list = ["a", "b", "c"]
for character in my_list:
    print(character)
for name in ["Chuck Norris", "Arnold Schwarzenegger", "Bruce Willis"]:
    print(name)
a
b
c
Chuck Norris
Arnold Schwarzenegger
Bruce Willis
In [77]:
# for loop over a range of integers
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
In [79]:
# for loop over characters in a string
for c in "Hello World":
    print(c)
H
e
l
l
o
 
W
o
r
l
d
In [80]:
# while loop - looping until a clause is fulfilled
a = 0
while a < 10:
    print(a)
    a += 1
0
1
2
3
4
5
6
7
8
9

Casting

In [85]:
# cast int to float
my_float = float(10)
print(my_float)
print(type(my_float))

# cast int to string
my_string = str(10)
print(my_string)
print(type(my_string))

# cast float to int
my_int = int(10.0)
print(my_int)
print(type(my_int))
10.0
<class 'float'>
10
<class 'str'>
10
<class 'int'>

Functions

Define a function

  • Function consists of a "head" and a "body"
  • Each function has a return value
  • If ommited: None is returned
  • Functions can have arguments
  • Recursion: functions can call themselves
In [87]:
# example function
def add(val1, val2):   # head
    return val1 + val2 # body

print(add(1, 2)) # function call
3
In [182]:
# function with no return value
def do_something(my_value):
    """
    This is a docstring of do_something
    It adds 15 to my_value and prints the result
    """
    result = add(my_value, 15)
    print(result)

do_something(1)

# you can call the explanation of the function
print(do_something.__doc__)
16

    This is a docstring of do_something
    It adds 15 to my_value and prints the result
    

Classes

  • Classes define templates for objects
  • Class member variables are accessible with: self.
  • To access member variables "self" has to be the first argument in a function of the class
In [181]:
# example class
class Car:
    """
    A class for cars
    """
    def __init__(self, manifacturer, doors): # constructor of the class
        self.manifacturer = manifacturer # set the class member manifacturer
        self.doors = doors
    
    def print_doors(self):
        print(self.doors)
        
    def get_values(self):
        return self.manifacturer, self.doors

# create an instance of the class
my_car = Car("Audi", 4)

print(my_car.manifacturer)
my_car.print_doors()
Audi
4

File processing

In [107]:
# read a file
filename = "file.txt"

# open the file in read only mode
fin = open(filename)

# read the complete file
text = fin.read()
print(text)
print(type(text))

# close the file
fin.close()
This is a test
Something Something
Foo
Bar

<class 'str'>
In [108]:
filename = "file.txt"
fin = open(filename)

# get all lines of the file
lines = fin.readlines()
print(lines)
print(type(lines))
['This is a test\n', 'Something Something\n', 'Foo\n', 'Bar\n']
<class 'list'>
In [110]:
# you can also use the scope variant

with open("file.txt") as fin: # opens the file
    text = fin.read()
    # the file is opend to this point
# here it is closed

print(text)
This is a test
Something Something
Foo
Bar

In [114]:
# write to a file

fout = open("writefile.txt", "w") # the "w" argument opens the file in "write" mode
fout.write("test") # due to the write mode - the file will be overwritten
fout.close()

with open("writefile.txt") as f:
    print(f.read())
    
print()
    
with open("writefile.txt", "a") as f: # the "a" argument opens the file in "append" mode
    f.write("\nanother line")

with open("writefile.txt") as f:
    print(f.read())
test

test
another line

Modules

Modules bundle python code together to enable easy access for other scipts

import provides the content of a module

Standard Python libraries and other external libraries can be imported

In [116]:
import sys # import of the module sys
sys.argv[0] # gives the first command line argument
Out[116]:
'/usr/lib/python3.6/site-packages/ipykernel_launcher.py'
In [117]:
# an element of the module can also be imported
from sys import argv
argv[0]
Out[117]:
'/usr/lib/python3.6/site-packages/ipykernel_launcher.py'
In [126]:
# some standard modules
import math # math functions
print(math.log(16,2)) # gives the binary logarithm of 10
print(math.pi)

import random # functions to generate random values
print(random.randrange(100)) # gives a random number in the range 0-99

import os # system functions
print(os.listdir(".")) # print a list of the files of the current directory
4.0
3.141592653589793
50
['python_tutorial.ipynb', 'writefile.txt', 'python.png', '.ipynb_checkpoints', 'file.txt']

Numpy

Numpy is a scientific library for python

It provides powerful functions to work with linear algebra such as arrays, vectors and matrices

Numpy Tutorial

In [18]:
import numpy as np # import numpy with an alias
In [147]:
matrix = np.matrix([[1,2],[1,2]]) # create a 2x2 matrix
print(matrix)
[[1 2]
 [1 2]]
In [131]:
my_array = np.array([1,2,3]) # create an array / vector
print(my_array)
[1 2 3]
In [19]:
my_range = np.arange(15) # create an numpy array containing values from 0-14
print(my_range)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
In [21]:
# reshape the range to a matrix
my_matrix = my_range.reshape(3,5) # reshape into matrix with 3 rows and 5 columns
print(my_matrix)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
In [148]:
# create a matrix with only 0 values
zero_matrix = np.zeros((3,4)) # 3x4 matrix
print(zero_matrix)
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
In [149]:
# create a matrix with only 1 values
one_matrix = np.ones((3,4)) # 3x4 matrix
print(one_matrix)
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
In [152]:
# get the shape of a matrix
print(one_matrix.shape)
(3, 4)
In [153]:
# get the size of a matrix
print(one_matrix.size)
12

Basic Numpy Operations

In [159]:
# addition
a = np.arange(4)
b = np.arange(4)
print(a)
print(b)

c = a + b # add b to a
print(c)
[0 1 2 3]
[0 1 2 3]
[0 2 4 6]
In [157]:
# subtraction
a = np.array([20,30,40,50])
b = np.arange(4)
print(a)
print(b)

c = a-b # subtract b from a
print(c)
[20 30 40 50]
[0 1 2 3]
[20 29 38 47]
In [163]:
# multiplication
a = np.arange(4)
print(a)

c = a * 2
print(c)
[0 1 2 3]
[0 2 4 6]
In [161]:
# exponentiation
b = np.arange(4)
print(b)
c = b**2
print(c)
[0 1 2 3]
[0 1 4 9]
In [164]:
# division
a = np.arange(4)
print(a)

c = a / 2
print(c)
[0 1 2 3]
[0.  0.5 1.  1.5]

Slicing in Numpy

In [169]:
a = np.arange(10)**3
print(a)

print(a[2]) # get the element at index 2

print(a[2:5]) # get the elements from index 2 to intex 4

print(a[: : -1]) # reverse a
[  0   1   8  27  64 125 216 343 512 729]
8
[ 8 27 64]
[729 512 343 216 125  64  27   8   1   0]
In [173]:
# multidimensional arrays

a = np.arange(20).reshape(5,4)
print(a)

print()

print(a[:, 1]) # get for each row element at index 1 - namely get the second column
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]

[ 1  5  9 13 17]

Splitting Arrays in Numpy

In [30]:
#### a = np.arange(20).reshape(5,4)
print(a)

print()

first,second = np.hsplit(a,2) # horizontal split into 2 arrays
print(first)
print(second)
#print(a,b,c,d)
#print(b)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]

[[ 0  1]
 [ 4  5]
 [ 8  9]
 [12 13]
 [16 17]]
[[ 2  3]
 [ 6  7]
 [10 11]
 [14 15]
 [18 19]]

Help in Python

help() calls the python help system

example: help(min) shows what the function min() does as long as the function has a docstring

Python2 vs Python3 example

In [5]:
# Python2 print
#print "Hello World"

# Python3 print
print("Hello World")

In this course we are going to use Python3!

Install Python3

Anaconda

Anaconda

How to install Python3 with Anaconda on Windows

How to install Python3 with Anaconda on Ubuntu

Or: use your packet manager

For Linux user it is more easy (eg. Ubuntu with pip):

sudo apt install python3

Or: install it by hand

Follow the instructions here

Use a Texteditor or IDE of your own choice

Install NumPy

with Anaconda

conda install -c anaconda numpy

with Pip

pip3 install numpy

Install Jupyter Notebook

Follow the instructions on this tutorial

Executing

execute python script:

python3 scriptname.py

with arguments:

python3 scriptname.py param1 param2