The Snake-Charmer Guide
git.io/JeuPA
Introduction
C
C++
Rust
Go
Javascript
PHP
Perl
Java
Python
Compiled
Interpreted
Introduction
def hello()
print("Hello, World!")
0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Hello, World!')
4 CALL_FUNCTION 1
Introduction
PHP
Slow
Fast
Easy
Hard
Python
Rust
C
Java
Javascript
C++
Go
Introduction
Introduction
most popular languages (stackoverflow 2022)
most loved languages (stackoverflow 2022)
Introduction
macOS
windows
linux
Ubuntu / Debian:
apt install python3
Arch / Manjaro:
pacman -S python3
Installation
VS Code
Atom
PyCharm
Vim oder Emacs are also fine of course 😉
with official python extension
with python extension
macOS
windows
linux
Applications/Utilities/Terminal.app
python3 + enter
Open the terminal
python3 + enter
Windows Key and type "cmd", hit enter
python + enter
Installation
# I'm a comment, everyone ignores me
a = "Hello 👋" # string
b = 5 # integer
c = True # boolean
Basics
# 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
}
# 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
# 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()
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 |
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 |
for x in range(0, 3):
print("Running 3 times 🏃🏼")
while True:
print('To infinity and beyond!')
Loops
# 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
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
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
function
x1
y
x2
add
1
3
2
def greet():
print("Hello 👋")
Functions
greet() # "Hello 👋"
def greet(name):
print(f"Hello {name} 👋")
Functions
greet('Python') # "Hello Python 👋"
greet('Batman') # "Hello Batman 👋"
def add(a, b):
addition = a + b
return addition
Functions
three = add(1, 2)
five = add(2, 3)
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 ❌
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') # ❌
name = 'Milka'
def hi():
print(f'Hi {name}')
hi()
Functions
name = 'Milka'
def hi():
name = 'Paula'
hi()
print(f'Hi {name}')
Functions
x = 0
def do_stuff():
x = 1
do_stuff()
print(x)
Functions
x = 0
def do_stuff():
x = x + 1
do_stuff()
print(x)
Functions
x = 0
def do_stuff():
global x
x = x + 1
do_stuff()
print(x)
Functions
# 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)
list = [1, 2, 3]
colors = ['blue', 'green', 'yellow']
mixed = [8, 'some string', True]
Basics
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
names = ["Peter", "Thomas", "Lisa", "Claire"]
for i, name in enumerate(names):
print(f"Person {i} is called {name}")
Basics
Basics
All methods are documents here:
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
{
key1: value1,
key2: value2,
...
}
Dict
person = {
'age': 900,
'name': 'Yoda'
}
Dicts
person = {
'age': 900,
'name': 'Yoda'
}
Dicts
person['age'] # 900
person['name'] # Yoda
person = {
'name': 'Yoda'
}
person['name'] # Yoda
person['name'] = 'Luke'
person['name'] # Luke
Dicts
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
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
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
class (1)
instance (0..n)
Person
Alice, Bob, ...
Car
Fiat, Tesla, ...
Mate
Club, Kolle, ...
class
attributes
methods
(variables)
(functions)
Classes
class Car:
pass
Classes
class Car:
def __init__(self):
pass
Classes
class Car:
def __init__(self, color):
self.color = color
Classes
my_first_car = Car('red')
my_second_car = Car('blue')
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()
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)
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
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.
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
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
Classes
https://docs.python.org/3/reference/datamodel.html
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.
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
SNAKE_CASE
CamelCase
lower_case_with_underscores
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
What happens when our programm runs into an error?
Exceptions
an Exception is raised
a = 2/0
# ZeroDivisionError
number = int(input("Enter a number: "))
# ValueError
song = {'name': "Sandstorm"}
darude = song['artist']
# KeyError
Error Handling
raise Exception()
raise Exception("I'm tired, don't want to work anymore")
def foo():
raise Exception("I decided to crash now")
Error Handling
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
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
class MyError(Exception):
pass
Error Handling
class MyError(Exception):
pass
try:
raise MyError()
except MyError:
print('Something happened')
Error Handling
a.k.a the interwebz
Python Standard Library
math, datetime, random
pypi.org
import datetime # Standard Library
timestamp = datetime.datetime.now()
print(timestamp)
Modules
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...
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()
# main.py
import ascii
ascii.order('Mate')
Modules
.
├── ascii.py
└── main.py
# ascii.py
def order(drink):
return f'Here is your {drink}'
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
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
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
Complex
One after another
Parallel waiting
Parallel doing
Parallel doing
in multiple places
<html>
<body>
<h1>Hello, I'm a title</h1>
<p>This is a paragraph.</p>
</body>
</html>
HTML
<html>
<body>
<h1>Some title</h1>
<div>
<p>
Some text
<b>
I am thick
</b>
</p>
</div>
</body>
</html>
HTML
<a href="https://tu-dresden.de">Go to uni 🔗</a>
HTML
<input type="text" placeholder="your name" />
HTML
<div> ... </div>
HTML
<div id="my-id" > ... </div>
<div class="my-class" > ... </div>
div
#my-id
.my-class
<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