Seminar 001: Python fundamentals¶
Welcome to Jupyter!¶
Jupyter is a coding environment that combines documentation and code which is very suitable for micropublications and to explain code. It is a new fundamental in scientific scripting that aids reproduciblity. Ultimately, Jupyter can help understanding what has been done better than a plain script.
There are two types of cells:
- Code: Here the actual code will be executed
- Markdown: Explanations and any kind of text that helps understanding the code
Each code cell can be executed individually by using the play-button or the key-combo shift
+ enter
. New cells can be added by using the plus-button (+) or the key-combo alt
+ enter
which will execute the current cell and add a new one.
Using Python as a calculator¶
2 * 2
4
Variables¶
- Variables act as "sticky notes" attached to any kind of data or result
- Most essential concept in programming
- Can be accessed later on by using the variables name
- Make sure to name your variable by its content
number = 2 * 2
# Jupyter specific (needs to be at the end)
number
4
# Print statement
print(number)
4
# Overload the print statement
print("This is the result: ", number)
This is the result: 4
# Combine variables
another_number = 20
print( "Multiplying the number by 'another_number': ", number * another_number )
Multiplying the number by 'another_number': 80
# Other operations
# Division
divided = 80 / another_number
print("Division: ", divided)
# Exponents
exponent = 80 ** 2
print("Exponent: ", exponent)
# Modulo
modulo = 80 % 2
print("Modulo: ", modulo)
Division: 4.0 Exponent: 6400 Modulo: 0
Data Types¶
- Numbers: Integers (int) and Floating Point Numbers (float)
- Strings: Collection of multiple characters (str)
# Integer
integer = 8
print( type(integer) )
<class 'int'>
# Float
floating_point = 8.0
print( type(floating_point) )
<class 'float'>
# Strings
string = "string"
print( type(string) )
<class 'str'>
# Doing operations with strings
string1 = "Hello, "
string2 = "World!"
string1 + string2
'Hello, World!'
# Get sub-strings
string = "Hello, world!"
print("First letter: ", string[0])
First letter: H
# Get the Hello sub-string
print("This is the hello: ", string[0:5])
This is the hello: Hello
# Casting of data types
floating_point = 10.6758
print("Cast the float to an integer: ", int(floating_point))
# The weird part of Python
int("10")
Cast the float to an integer: 10
10
# This cast does not work!
int("ten")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-23-5db6fed51cc0> in <cell line: 2>() 1 # This cast does not work! ----> 2 int("ten") ValueError: invalid literal for int() with base 10: 'ten'
Lists¶
- Contains a sequence of arbitrary data types
- Started with
[
followd by comma-separated entries and closed by]
- Individual entries can be accessed using
int
indicies (my_list[0]
for the first entry) - Order is important
# You were in the lab and recorded a measurement
time1 = 0.0
time2 = 2.0
time3 = 5.0
# Lists are arrays of things
measurement = [ 0.0, 2.0, 5.0 ]
print(measurement)
[0.0, 2.0, 5.0]
print("First element: ", measurement[0])
First element: 0.0
print("First to second element: ", measurement[0:2])
First to second element: [0.0, 2.0]
# Adding things to lists
measurement.append(10.0)
print("After appending: ", measurement)
After appending: [0.0, 2.0, 5.0, 10.0]
# We can add whatever we want
# It is not type specific!
measurement.append("Feierabend!")
print("After appending: ", measurement)
After appending: [0.0, 2.0, 5.0, 10.0, 'Feierabend!']
# Extract the last element of a list
print("The last element: ", measurement[-1])
The last element: Feierabend!
Dictionaries¶
- Mapping from a
key
to avalue
- Can be regarded as a collection of "sticky notes"
- Behaves similar to a list, but that the indices are generalized to custom indices
- Order is not important
# Dict is a generlization of a list
# list[1] = something
metadata = {"name": "Jan"}
print(metadata["name"])
Jan
# Lets implement a list as a dict
fake_list = {0: 0.0, 1: 2.0}
print("First entry: ", fake_list[0])
First entry: 0.0
For-loops¶

- Used to dynamically iterate over each entry in a list or dictionary
- Helps solving the problem of individual accessing a list
- Most used loop in Python and staright forward
Procedure¶
- The for-loop "pulls" an entry per round from the list
- Stored in the "variable scope" to the name you've choosen e.g.
variable
- Inside the "body" operations can be executed as usual
Example¶
for variable in my_list:
# do something
print(variable * 2)
# Access values in a list
measurement = [0.0, 2.0, 5.0, 10.0]
measurement[0]
measurement[1]
measurement[6]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-39-cee00ed135c6> in <cell line: 6>() 4 measurement[0] 5 measurement[1] ----> 6 measurement[6] IndexError: list index out of range
# Use a for loop!
for number in measurement:
print("Current number: ", number)
print("Do something: ", number * 10)
print("Unindented: ", number)
Current number: 0.0 Do something: 0.0 Current number: 2.0 Do something: 20.0 Current number: 5.0 Do something: 50.0 Current number: 10.0 Do something: 100.0 Unindented: 10.0
# Dont forget indenting! This does not work
for number in measurement:
print(number)
File "<ipython-input-56-a79a2f00f890>", line 4 print(number) ^ IndentationError: expected an indented block after 'for' statement on line 3
While-loops¶

- Behaves similar to the for-loop
- Stops whenever a specific condition is met, such as when a number is greater some value
- Does not pull entries from a list, thus it needs to be done manually
- Needs a starting condition that is evaluated at each round
- Can end up in an infinite loop
- Rarely used and should only be considered when dealing with highly dynamic tasks
Procedure¶
- Set up a starting condition and a termination condition
- Enter the body of the loop and perform the operation
- At the next iteration, the condition is tested
- If met, the loop continues. If not, the loop is terminated
Example¶
index = 0
while index <= 10:
print(index)
# Index needs to be increased manually
index += 1
measurements = [0.0, 5.0, 10.0]
index = 0
while index < 3:
number = measurements[index]
print("At index ", index, " is number ", number)
# Need to increment, otherwise infinite loop!
index += 1
At index 0 is number 0.0 At index 1 is number 5.0 At index 2 is number 10.0
Conditions¶
- If-else statements are very important to deal with certain situations
- Whenever a condition is met, the following code is executed
- Optionally, an
else
statement can be used to deal with all situations that did not match the condition
Using conditions wisely¶
- Try to use as less as possible and as much as needed
- Nesting too many
if
s is a sign of bad design - Sometimes it is helpful to deal with what you dont want (see Guard clauses)
# String comparisons
names = ["Daniel", "Alan", "Marie", "Sara"]
for name in names:
# If statements should always evaluate
# to a boolean (True/False)
if True:
print(name)
# String comparisons
names = ["Daniel", "Alan", "Marie", "Sara"]
for name in names:
if name[0] == "D":
print(name)
Daniel
# Numerical conditions
measurements = [0.0 , 5.0, 6.0, 20.0, 50.0]
for number in measurements:
if number < 20.0:
print(number)
elif number == 20.0:
print("This should be 20! ", number)
else:
print("Dunno what to do!", number)
0.0 5.0 6.0 This should be 20! 20.0 Dunno what to do! 50.0
Its all about the sauce¶
Navigating through the syntax jungle can be quite tempting and exhausting. However, most problems you will be confronted with have already been solved numerous times. Thus, knowing your sources is the utmost important skill when programming. There are multiple sites where problems are discussed and solutions are given!
Helpful sites¶
- StackOverflow - Probably the best site to search for help
- W3Schools Python - Great overview of Pythons functionality
- PythonCheatSheet - Another great overview
- Google - The most used tool in Software Development