Python
The Snake-Charmer Guide
A bit about you
- Deutsch / English?
- Ersti?
-
Why do you want (have 😉) to take this course?
- Interest
- RoboLab
Resources
git.io/JeuPA
Where is Python? 🐍
Introduction
C
C++
Rust
Go
Javascript
PHP
Perl
Java
Python
Compiled
Interpreted
Bytecode
Introduction
def hello()
print("Hello, World!")
0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Hello, World!')
4 CALL_FUNCTION 1
Where is Python? 🐍
Introduction
PHP
Slow
Fast
Easy
Hard
Python
Rust
C
Java
Javascript
C++
Go
But it is so slow! 🐢
- developer time is a lot more expensive than computing time
- many applications are not bound by processing time
- many algorithms implemented in C
Introduction
State of Python 📈
Introduction
most popular languages (stackoverflow 2022)
most loved languages (stackoverflow 2022)
Why Python? 🤔
- Easy & Intuitive
- Huge community
- Robolab
- Mature Packages for almost everything
(202.022 @ 10.2019 ... 403.290 @ 07.2022)
Introduction
Installation
macOS
windows
linux
Ubuntu / Debian:
apt install python3
Arch / Manjaro:
pacman -S python3
Editor / IDE
Installation
VS Code
Atom
PyCharm
Vim oder Emacs are also fine of course 😉
with official python extension
with python extension
Open Python
macOS
windows
linux
Applications/Utilities/Terminal.app
python3 + enter
Open the terminal
python3 + enter
Windows Key and type "cmd", hit enter
python + enter
Installation
Variables
# I'm a comment, everyone ignores me
a = "Hello 👋" # string
b = 5 # integer
c = True # boolean
Basics
Types
# Strings
'Python'
"Another String"
"""I
am
incredibly
long
"""
# Boolean
True
False
Basics
# Integer
1
42
69
-420
123e3 # 123000
# Float
0.123
0.5e2 # 50.0
# List
[1, 2, 3]
["foo", "bar"]
[True, 2, "three"]
# Tuples
("Hello", 2)
# Dictionaries
{
'name': 'Yoda',
'age': 900
}
Built-ins
# Conversion
int(5.3) # 5
int(5.7) # 5
float(5) # 5.0
int('5') # 5
float('5.5') # 5.5
# Length
len('Hello') # 5
len([1,2,3]) # 3
Basics
Control Flow
# if & else
if something is True:
do_this()
else:
do_that()
# and
if a and b:
do_this()
# or
if (a and b) or c:
do_this()
Basics
# numbers
if 42 < 69:
magic()
# numbers
if 42 == 42:
magic()
# string
if input == 'awesome':
yaaas()
else:
nope()
Reserved Words
Basics
and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
Terminal for Dummies
Command | macOS / Linux | Windows |
---|---|---|
navigate | cd | cd |
list files & directories | ls | dir |
create folder | mkdir | mkdir |
create files | touch test.txt | type nul > test.txt |
remove files | rm | del |
remove folder | rm -r myfolder | rmdir \s myfolder |
run python | python3 hello.py | python hello.py |
Loops
Overview
for x in range(0, 3):
print("Running 3 times 🏃🏼")
while True:
print('To infinity and beyond!')
Loops
For
# range(start, end) generates numbers from `start` to `end`
# `start` is included, but `end` is not
# => range(0, 3) will generate 0,1,2
for x in range(0, 3):
print(x) # 0,1,2
for x in range(3):
print(x) # 0,1,2
for name in ['Lisa', 'Günther', 'Sigfriede']:
print(name) # Lisa, Günther, Sigfriede
Loops
While
n = 5
while n > 0:
print(n)
n -= 1
# 5,4,3,2,1
while True:
# forever
l = ['A', 'B', 'C']
while l:
element = l.pop() # Change l "in-place" until it's empty (=false)
print(element)
# A, B, C
Loops
Controls
l = [1, 2, 3, 4, 5]
for x in l:
if l == 3:
break
print(x)
# 1,2
for x in l:
if l == 3:
continue
print(x)
# 1,2,4,5
Loop
Functions
- Reuse logic & code
- Readability
- Split up complex tasks
function
x1
y
x2
add
1
3
2
Declaration
def greet():
print("Hello 👋")
Functions
greet() # "Hello 👋"
Parameters
def greet(name):
print(f"Hello {name} 👋")
Functions
greet('Python') # "Hello Python 👋"
greet('Batman') # "Hello Batman 👋"
Example
def add(a, b):
addition = a + b
return addition
Functions
three = add(1, 2)
five = add(2, 3)
Default Values
def add(a, b=1):
addition = a + b
return addition
Functions
three = add(1, 2)
five = add(4)
def add(a, b):
addition = a + b
return addition
five = add(4)
# ❌ ERROR ❌
Named Parameters
def eat(pizza, slices):
print(f"Eating a pizza {pizza} with {slices} slices")
Functions
eat('Margherita', 8) # ✔
eat(pizza='Margherita', slices=8) # ✔
eat(slices=8, pizza='Margherita') # ✔
eat('Margherita', slices=8) # ✔
eat(slices=8, 'Margherita') # ❌
Scope
name = 'Milka'
def hi():
print(f'Hi {name}')
hi()
Functions
Scope
name = 'Milka'
def hi():
name = 'Paula'
hi()
print(f'Hi {name}')
Functions
Scope
x = 0
def do_stuff():
x = 1
do_stuff()
print(x)
Functions
Scope
x = 0
def do_stuff():
x = x + 1
do_stuff()
print(x)
Functions
Scope
x = 0
def do_stuff():
global x
x = x + 1
do_stuff()
print(x)
Functions
Overview
# Simple
def hello():
print('Hello')
# Parameter
def greet(name):
print('Hello ' + name)
greet('Horst')
Functions
# Return
def add(a, b):
return a + b
c = add(1, 2)
# Named Parameters
def gradient(x, y):
return y / x
m = gradient(y=5, x=10)
Lists
- Reuse logic & code
- Readability
- Split up complex tasks
List
list = [1, 2, 3]
colors = ['blue', 'green', 'yellow']
mixed = [8, 'some string', True]
Basics
List
list = [1, 2, 3]
first = list[0]
last = list[-1]
first_two = list[0:2]
first_two = list[:2]
last_two = list[-2:]
everything_except_the_first = list[1:]
everything_except_the_last = list[:-1]
Basics
List
names = ["Peter", "Thomas", "Lisa", "Claire"]
for i, name in enumerate(names):
print(f"Person {i} is called {name}")
Basics
List
Basics
All methods are documents here:
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
Dicts
- A.k.a Maps
- Key-Value pairs
- Group data together
- Less variables
What?
Why?
Syntax
{
key1: value1,
key2: value2,
...
}
Dict
Assignment
person = {
'age': 900,
'name': 'Yoda'
}
Dicts
Reading
person = {
'age': 900,
'name': 'Yoda'
}
Dicts
person['age'] # 900
person['name'] # Yoda
Writing
person = {
'name': 'Yoda'
}
person['name'] # Yoda
person['name'] = 'Luke'
person['name'] # Luke
Dicts
Iterating
person = {
'name': 'Elon Musk',
'age': 48,
'height': 184,
'worth': '23,7 Billion',
'companies': ['Paypal', 'SpaceX', 'Tesla']
}
for key in person.keys():
print(key) # name, age, height, worth, companies
for value in person.values():
print(value) # Elon Musk, 48, 184, ...
for key, value in person.items():
print(f'{key} has the value: {value}')
# name has the value Elon Musk
# age has the value 48
# ...
Dicts
Nesting
person = {
'name': 'Elon Musk',
'age': 48,
'height': 184,
'worth': '23,7 Billion',
'companies': {
'Paypal': {
'founded': 2000,
'revenue': '15.451 billion',
'employees': 21800
},
'SpaceX': {
'founded': 2002,
'revenue': '2 billion',
'employees': 7000
},
'Tesla': {
'founded': 2003,
'revenue': '21.461 billion',
'employees': 45000
}
}
}
Dicts
List Comprehensions
Is it a map? Is it a filter? No, it's both!!
# Option 1: For loop
squares = []
for x in range(10):
squares.append(x*x)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Option 2: Map()
def square(x):
return x*x
squares = list(map(square, range(10)))
# Option 3: List comprehension
squares = [x*x for x in range(10)]
# │ │ └ Existing list
# │ └ Iteration variable (similar to for loop)
# └ The transformation for each element
Classes
- Group functions and variables together
- Basis of Object Oriented Programming (OOP)
- Group logic that belongs together
- Domain specific code
- Extendable
What?
Why?
class (1)
instance (0..n)
Person
Alice, Bob, ...
Car
Fiat, Tesla, ...
Mate
Club, Kolle, ...
class
attributes
methods
(variables)
(functions)
Person
Classes
Class
Instance
- Alice, 20
- Bob, 7
- Charlie, 43
- Diana, 32
- Name
- Age
- Static: Homo sapiens
Basics
class Car:
pass
Classes
Constructor
class Car:
def __init__(self):
pass
Classes
Attributes
class Car:
def __init__(self, color):
self.color = color
Classes
my_first_car = Car('red')
my_second_car = Car('blue')
Methods
class Car:
def __init__(self, color):
self.color = color
def clean(self):
print(f'I am {self.color} again!')
Classes
my_first_car = Car('red')
my_first_car.clean()
my_second_car = Car('blue')
my_second_car.clean()
Static Attributes
class Car:
wheels = 4
def __init__(self, color):
self.color = color
def clean(self):
print(f'I am {self.color} again!')
Classes
my_first_car = Car('red')
print(my_first_car.wheels)
my_second_car = Car('blue')
print(my_second_car.wheels)
Example
class Car:
wheels = 4
capacity = 5
def __init__(self, color):
self.color = color
self.passengers = 0
def clean(self):
print(f'I am {self.color} again!')
def get_in(self, how_many):
self.passengers += how_many
def available_seats(self):
available = self.capacity - self.passengers
print(available)
Classes
my_first_car = Car('blue')
my_second_car = Car('red')
my_first_car.available_seats() # 5
my_first_car.get_in(1)
my_first_car.available_seats() # 4
my_first_car.get_in(3)
my_first_car.available_seats() # 1
my_second_car.available_seats() # 5
__str__
class Car:
def __init__(self, model):
self.model = model
def __str__(self):
return f"This is a {self.model}."
Classes
fiat_1 = Car('Fiat 500')
fiat_2 = Car('Fiat 500')
vw = Car('VW Golf')
print(fiat_1)
print(fiat_2)
print(vw)
# This is a Fiat 500.
# This is a Fiat 500.
# This is a VW Golf.
__eq__
class Car:
def __init__(self, model):
self.model = model
def __str__(self):
return f"This is a {self.model}."
def __eq__(self, other: object) -> bool:
return self.model == other.model
Classes
fiat_1 = Car('Fiat 500')
fiat_2 = Car('Fiat 500')
vw = Car('VW Golf')
print(fiat_1 == vw)
print(fiat_1 == fiat_2)
# False
# True
print(fiat_1 == fiat_2)
print(fiat_1 is fiat_2)
# True
# False
__gt__
class Car:
def __init__(self, model, length):
self.model = model
self.length = length
def __str__(self):
return f"This is a {self.model}."
def __eq__(self, other: object) -> bool:
return self.model == other.model
def __gt__(self, other: object) -> bool:
return self.length > other.length
Classes
fiat = Car('Fiat 500', 3.6)
vw = Car('VW Golf', 4.2)
print(fiat > vw)
print(vw > fiat)
# False
# True
Class Overwrites
- Basic: init, repr, str, bool
- Comparison: lt, le, gt, ge, eq, ...
- Math: add, sub, mul, div, ...
- Utility: len, iter, contains, ...
- Even further: call
Classes
https://docs.python.org/3/reference/datamodel.html
Inheritance
class Car:
def __init__(self, seats):
self.seats = seats
self.odometer = 0
def drive(self, km):
self.odometer += km
def __str__(self):
return f'I have driven {self.odometer}km.'
class Truck(Car):
def __init__(self, seats, capacity):
super().__init__(seats)
self.capacity = capacity
def load(self, kg):
self.capacity -= kg
def __str__(self):
return f'I have driven {self.odometer}km and have {self.capacity}kg of space left.'
Classes
car = Car(4)
car.drive(100)
print(car)
# I have driven 100km.
truck = Truck(2, 100)
truck.load(25)
truck.drive(50)
print(truck)
# I have driven 50km and have 75kg of space left.
Inheritance
class Car:
pass
class Truck(Car):
pass
car = Car()
truck = Truck()
Classes
print(isinstance(car, Car)) # True
print(isinstance(truck, Car)) # True
print(isinstance(car, Truck)) # False
print(isinstance(truck, Truck)) # True
Naming Conventions
- How do i call x?
- variables, functions, parameters, etc.
- It's a convention, not a requirement
- Makes it easier to read code
- Especially if it's not yours
What?
Why?
Cases
Naming Conventions
SNAKE_CASE
CamelCase
lower_case_with_underscores
Example
myVariable = 'foo' # 👎
MyVariable = 'foo' # 👎
my_variable = 'foo' # 👍
MY_CONSTANT = 'foo' # 👍 , but not only for constants
def some_function(some_parameters): # 👍
pass
# Classes
class SomeClass:
pass
Naming
Error handling
What happens when our programm runs into an error?
Exceptions
an Exception is raised
Common Exceptions
a = 2/0
# ZeroDivisionError
number = int(input("Enter a number: "))
# ValueError
song = {'name': "Sandstorm"}
darude = song['artist']
# KeyError
Error Handling
Raise an Exception
raise Exception()
raise Exception("I'm tired, don't want to work anymore")
def foo():
raise Exception("I decided to crash now")
Error Handling
Handle it
def try_not_to_procrastinate():
raise Exception("This 30 minute Youtube video about Ant colonies looks really nice!")
try:
try_not_to_procrastinate()
except Exception:
print("Well...")
# # Well...
Error Handling
Handle it
def try_not_to_procrastinate():
raise Exception("This 30 minute Youtube video about Ant colonies looks really nice!")
try:
try_not_to_procrastinate()
except Exception as e:
print(e)
# This 30 minute Youtube video about Ant colonies looks really nice!
Error Handling
Custom Errors
class MyError(Exception):
pass
Error Handling
Custom Errors
class MyError(Exception):
pass
try:
raise MyError()
except MyError:
print('Something happened')
Error Handling
Modules & Imports
- Split code into multiple files
- Use code that people have already written
- Don't reinvent the wheel
- Much easier to maintain
- Keeps everything organised
What?
Why?
Python
PIP
a.k.a the interwebz
Local
Python
- Batteries Included
- 250+ Build-In Packages
Python Standard Library
math, datetime, random
PIP
- 208,439 projects
- 1,576,568 releases
- 2,362,966 files
- 390,584 users
pypi.org
Basics
import datetime # Standard Library
timestamp = datetime.datetime.now()
print(timestamp)
Modules
Import
import math
Modules
math.sqrt(4) # 2
math.ceil(2.1) # 3
math.floor(2.1) # 2
math.pi # 3.14159...
math.cos(math.pi) # -1.0
from math import sqrt, pi
sqrt(4) # 2
math.ceil(2.1) # ❌ Error
pi # 3.14159...
Aliasing
import something
something.do()
Modules
from something import do
do()
import something as s
something.do() # ❌
s.do() # ✅
from something import do as foo
foo()
Import own code
# main.py
import ascii
ascii.order('Mate')
Modules
.
├── ascii.py
└── main.py
# ascii.py
def order(drink):
return f'Here is your {drink}'
Asynchronous Programming
Synchronous
print('Guess my number!') # This one is always executed first
rounds = 1
found = False
start = time.time()
while True:
try:
# Blocks the current thread until the user has
# entered something.
# => We can't do anything in the meantime.
guess = input('What is your guess?: ')
guess = validate_guess(guess) # May throw a ValueError
is_correct = play_round(guess) # May throw a InvalidGuess
if is_correct:
found = True
break
rounds += 1
except ValueError as e:
print('You are too dumb for this game, it says NUMBER!')
break
except InvalidGuess as e:
print('INVALID: ', e)
print('Please try again. 🙏')
continue
EMAIL EXAMPLE!!!
Task:
- We have to do 10 conversations
- For each conversation:
- We send a question (little time)
- Recipient answer (a lot more time)
- We send a confirmation (little time)
Me: Question 0
They: Info 0
Me: Ok 0
Synchronous (Naive)
Process & Thread
Process 1
CPU 1
CPU 2
Thread
Thread
Time
Process 2
Thread
Thread
- Processes run on a single CPU
- Process request resources (CPU, memory, etc.)
- Thread is an instance of a process that has all resources (hence, it can run)
-
Threads are stopped by OS when:
- time slice is exhausted (20ms)
- thread blocks because it waits for something
-
Threads are started by OS when:
- they are the next in the queue
- some event for which the thread has waited happened
Why is it slow?
compute-bound
memory-bound
IO-bound
Your computer does not have enough processing power to handle the task.
e.g. Your processor can do 100 iterations of something an hour, but the task is to do 10,000,000 a day.
Your computer does not have enough memory to store all values.
e.g. You have 16Gb of RAM but need 12 TB to store all the values.
Your processor is doing almost nothing and is waiting for input and/or output to happen.
e.g. Writing large data to disk, fetch information from the internet.
Solution:
- parallel computing
- distributed computing
Solution:
- more money
- declare it as a feature
- back to the drawing board
Solution:
- async programming
(parallel waiting)
- multi-threading
Computation approaches
Easier
Complex
Synchronous
Multithreading
Asynchronous
Parallel
Distributed
One after another
Parallel waiting
Parallel doing
Parallel doing
in multiple places
HTML
- Similar syntax to XML
- Born in 1993
Hello world
<html>
<body>
<h1>Hello, I'm a title</h1>
<p>This is a paragraph.</p>
</body>
</html>
HTML
Hierarchy
<html>
<body>
<h1>Some title</h1>
<div>
<p>
Some text
<b>
I am thick
</b>
</p>
</div>
</body>
</html>
HTML
Attributes
<a href="https://tu-dresden.de">Go to uni 🔗</a>
HTML
Attributes
<input type="text" placeholder="your name" />
HTML
Selectors
<div> ... </div>
HTML
<div id="my-id" > ... </div>
<div class="my-class" > ... </div>
div
#my-id
.my-class
Selectors
<div>
<div id="some" > ... </div>
</div>
HTML
<div id="my-id" >
<p>
<span class="text" >Some text</span>
</p>
</div>
div #some
#some
div p span
#mi-id p span
div span
#my-id span
#my-id .text
.text
The Snake-Charmer Guide
By cupcakearmy
The Snake-Charmer Guide
- 571