---
language: python
category: Language / Tutorial
---
title: Hello World
descr: The "Hello World" program
code: print("Hello World")
---
title: Objects/Instances
descr: >
One of the most fundamental building blocks of a Python program are "Objects".
They are concrete "instances" of a certain type.
As a real-world analogue, you can think of a pair of shoes as a type,
and the specific example of shoes you are wearing right now as an instance of that type.
Your specific shoes also have certain properties, like a specific size, a color, a make, maybe even a serial number, etc.
The type "shoe" would only describe these properties, while a specific pair has concrete values.
More about this at a later point.
code: |
"hello" # creates an object of type "string" with the value "hello"
5.5 # the floating point number 5.5
---
title: Variables
descr: >
A variable is a name for an object.
It is done via this syntax:
```
variablename = object
```
`print` is a function to show the object as a string.
code: |
x = 1
y = x + 1
print(x)
print(y)
---
title: Print Data
descr: The "Hello World" program printing some values.
code: |
x = "Hello"
y = 2.123456789
print("%s World, y = %f" % (x, y))
print("x={x}, y={y:.3f}".format(**locals()))
---
title: Expressions
descr: >
Expressions are constructued by combining several object.
Usually, they can be evaluated, because operators and functions are used to build the expression.
Furthermore, use parenthesis to control the order of the evaluation!
code: |
print((5 + 6) * 11)
z = 3 # assign a variable, then use it in an expression
print((1 + z)**2)
from math import sqrt
print(sqrt(z))
---
title: Functions
descr: >
A function call is one of the most basic levels of abstraction.
A common subroutine of evaluations is run with varying initial arguments.
The `return` statement is very important: data flows back to where the functions has been called.
code: |
def function1(x, y):
z = 10 * x + y
return z
print(function1(4, 5))
print(function1(1,-1))
---
title: Functions (nested)
descr: >
It is fine to nest functions in more complex expressions.
code: |
def foo(x):
return 2*x+1
print(foo(1 + foo(3)) - 2)
---
title: "Data Structure: List"
descr: >
To organize information in a program, data structures are here to help.
A very basic one is an ordered collection of arbitrary objects.
Such a `list` object is constructed by listing objects between `[ ... ]` delimited by a commas `,`.
code: |
x = [42, "Hello", [1,2,3]]
print(x)
x.append("World")
print(x)
---
title: "List access"
descr: >
To access elements at a specific location, use `[]` brackets with the index number.
Counting starts at zero and negative values index in the other direction from the end.
Also be aware, that like with functions lists might also be nested.
code: |
l = [4, 5, -1, 2]
print(l[1])
print(l[-1])
print(l[0] + 2 * l[1])
---
title: "Control Structure: if/else"
descr: >
Code is executed line by line, but it can be directed to flow in more complex ways.
An `if` decides if a block of code is executed, or – together with `else` – decides between two blocks.
In Python, blocks are indented by spaces (usually two or four) from the beginning for the line.
Nested blocks are indented multiple times (4 or 8 times, etc.).
code: |
x = -8
print('x is %s' % x)
if x > 0: # note the colon!
print('x is positive')
else:
print('x is not positive')
print('this line is always executed!')
# TODO: change the -8 to a positive value and see how the flow changes
---
title: "Control Structure: for"
descr: >
A `for`-loop repeates a block of code by consecutively assigning a local variable with values from a list or iterator.
code: |
for i in ['a', 'c', 'abc', 'x']:
print("variable i is %s" % i)
for j in range(3):
for k in range(5):
print("j: {} + k: {} = {}".format(j, k, j+k))
---
title: "Data Structure: Dict(ionary)"
descr: >
A dictionary is an mapping of (immutable) objects to arbitrary objects.
The immutable objects are called "keys" and are most commonly numbers, strings or tuples.
To set a key in a dictionary, assign it like this: `var["x"] = 42`.
Later, accessing a dictionary is similar to a list:
`var["x"]` retrieves the entry with the name `"x"` from the dictionary referenced by the variable `var`.
As by the assignment above, the retrived object is the number `42`.
code: |
d = dict()
d[42] = "The Answer"
d["what"] = ["this", "and", "that"]
d[(4, 2)] = 99
print(d[42])
print(d[(4,2)])
print(d.keys())
print(42 in d)
---
title: "Classes"
descr: >
A `class` is the usual way how someone can define a custom `type`.
We define a class `Shoe` with a specific color and size.
Under the hood, a class is like a dictionary but with some extras and an enhanced syntax.
Additionally, "methods" are functions in a class.
They are used to compute a derived value from the data of an instantiated object.
The method `__init__` is special: it is called upon instantiation and used to set the values of the object.
code: |
class Shoe(object):
def __init__(self, size, color):
self.size = size
self.color = color
def double(self):
"""return twice the size of the shoe"""
return 2 * self.size
# instantiation:
s1 = Shoe(40, "green")
s2 = Shoe(43, "black")
print(s1.color)
print(s2.double())
print(type(s2)) # the type of the object referenced by s1 is "Shoe"