About Python, variable types and script execution. For interactive reading and executing code blocks and find b01-pybase.ipynb, or install Python and JupyterLab locally.
Watch this section as a video
Watch this section as a video on the @Hydro-Morphodynamics channel on YouTube.
Python-Umgebung laden¶
These pages are written with JupyterLab . For the best learning experience make sure to read about Integrierte Entwicklungsumgebungen (IDE) before starting this tutorial.
Die ersten Zeilen des Codes¶
Die Beispiele in den ersten Schritten drehen sich um Eiscreme, um den Nutzen einfacher Code-Schnipsel zu veranschaulichen. Wenn Sie kein Eis mögen, ersetzen Sie es mit Ihrer Lieblingskategorie von Dingen.
Letztendlich sind Sie bereit, die allererste Antwort (Ausgabe) von der Python-Konsole zu erhalten. Beginnen Sie mit einem einfachen Aufruf der Funktion print, indem Sie Folgendes eingeben:
print("This is output from the digital ice cream printer.")This is output from the digital ice cream printer.
Recall that the print command, like all other Python commands that will follow, can be either run in a Python console (e.g., Conda Prompt on Windows or Terminal on Linux) or in your favorite IDE. In addition, we can write down the print command in a Python file ending on .py (e.g., icecream_tutorial.py) and run the file. For instance, in PyCharm:
Erweitern Sie den Projektzweig (falls noch nicht fertig: auf der linken Seite des Fensters)
Klicken Sie mit der rechten Maustaste in den Projektordner, wählen Sie
New>Python Fileund benennen Sie die neue Python (.py) Datei (z. B.icecream_tutorial.py).Copy the above
print("...")code into the new Python file and save it.Klicken Sie mit der rechten Maustaste in die Python-Datei, dann
Run icecream_tutorial.py(alternativ: drücken Sie die TastenCtrl+Shift+F10).Now, the Python Console should pop up at the bottom of the window and it will print the text in the above
printcommand.
In jedem anderen (IDE) Terminal, cd in das Verzeichnis, in dem die Python-Datei (icecream_tutorial.py) lebt, geben Sie dann python icecream_tutorial.py ein und drücken Sie Enter.
With the " apostrophes in the print command, we pass a string variable to the print command. Instead of using ", one can also use ', but it is important to use the same type of apostrophe at the beginning and the end of the string (text) variable.
A marginal note: In Python3 print is a function, not a keyword as in Python2. print is useful, for example, to make a script show where it is currently running. It is also possible to print other types of variables than strings, but the combination of numerical and text variables requires more encoding (see next sections).
Python Variablen und Datentypen¶
The above-shown print function already involved string variables. In addition, there are a couple of other variable (data) types in Python:
Text
Boolean
Zahl (numerisch)
Tupel
Liste
Wörterbuch
Text¶
Textvariablen in Python sind Strings (str), die aus mehreren Zeichen (chr) bestehen:
| Typ | Beispiel | Beschreibung |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| str | "apple" | String umarmt mit doppelten Zitaten |
| | 'apple' | String umarmt mit einzelnen Zitaten |
| | """apple""" | Literale Zeichenfolge (mehrzeiliger Text) |
| chr | "a" | Zeichen (Einheit einer Zeichenfolge) |
| Type | Example | Description |
|------|:-----------:|------------------------------------|
| str | `"apple"` | String embraced with double quotes |
| | `'apple'` | String embraced with single quotes |
| | `"""apple"""` | Literal string (multi-line text) |
| chr | `"a"` | Character (unit of a string) |
In addition, string variables have some built-in functions that facilitate coding. To create (instantiate) a string variable, use the = sign as follows:
flavor1 = "vanilla" # str
first_letter = "v" # str / char
print(flavor1.upper())
print(flavor1[0])
print(flavor1.split("ll")[0])VANILLA
v
vani
Characters can be converted to numbers and the other way round. The built-in ord() function returns the Unicode code point of a character, and chr() does the reverse. This is useful, for example, to iterate over alphabetically ordered lists.
print(ord("c")) # character -> integer (Unicode code point)
print(chr(99)) # integer -> character99
c
Boolean¶
Boolean variables are either True (1) or False (0) with many useful code implementations. We will come back to booleans (bool) later in the section on conditional (if ...) statements.
bowl = False
print("The bowl exists: " + str(bowl))The bowl exists: False
Anzahl (numerisch)¶
Python kennt einige verschiedene numerische Datentypen:
| Typ | Beispiel | Beschreibung |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| int | 10 | Signed Integer |
| float | 5.382 | Floating Point real number |
| complex | 1.43j | Komplexe Zahl; j (oder J) bezeichnet die imaginäre Einheit |
To create a numeric variable, use the = sign as follows:
scoops = 2 # int
weight = 0.453 # floatPython erfordert keine Typzuweisung für eine Variable, da es ** eine hoch interpretierte Programmiersprache** ist (andere als zum Beispiel C++). Sobald einer Variable jedoch ein Datentyp zugewiesen wurde, ändern Sie sie nicht im Code (es ist nur eine gute Praxis - so dass Schaufeln Ganzzahlen bleiben).
Wenn eine Druckanweisung numerische und Textvariablen kombiniert, müssen die numerischen Variablen zuerst in Text konvertiert und dann concatenated zu einem String. Es gibt mehrere Möglichkeiten, mehrere Variablen in einer Textzeichenfolge zu kombinieren:
print("My ice cream consists of %d scoops." % scoops) # use %d for integers, %f for floats and %s for strings
print("My ice cream weighs %1.3f kg." % weight)
print("My ice cream weighs " + str(weight) + " kg.")
print("My ice cream weighs {0} kg and has {1} scoops".format(weight * scoops, scoops)) # multiple variable conversion
# f-strings (Python 3.6+) are the modern, preferred way to format text:
print(f"My ice cream weighs {weight:.3f} kg and has {scoops} scoops.")My ice cream consists of 2 scoops.
My ice cream weighs 0.453 kg.
My ice cream weighs 0.453 kg.
My ice cream weighs 0.906 kg and has 2 scoops
My ice cream weighs 0.453 kg and has 2 scoops.
print("My ice cream weighs " + weight + " kg.") # this cannot work because weight is a float---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 print("My ice cream weighs " + weight + " kg.") # this cannot work because weight is a float
TypeError: can only concatenate str (not "float") to strListe¶
A list is a series of values, which is embraced with brackets []. The values can be any other data type (i.e., numeric, text, dictionary, or tuple), or even another list (so-called nested lists).
flavors = ["chocolate", "bread", flavor1] # a list of strings
nested_list = [[1, 2, 3], ["a", "b", "c"]]
print(nested_list)
print("A list of strings: " + str(list("ABC")))[[1, 2, 3], ['a', 'b', 'c']]
A list of strings: ['A', 'B', 'C']
Die Elemente einer Liste heißen Einträge und Einträge können angehängt, eingefügt oder aus einer Liste gelöscht werden.
Auch Listen haben viele nützliche eingebaute Funktionen:
flavors.append("cherry") # append an entry at the end
print(flavors)
flavors.insert(0, "lemon") # insert an entry at position 0
print(flavors)
print(f"There are {len(flavors)} flavors in my list.")
print(*flavors) # print all elements of the list (note: cannot be concatenated to a str)
print("This is all I have: " + str(flavors[:]).strip("[]"))
del flavors[2] # bread is not a flavor, so let's remove it
print("This is all I have: " + ", ".join(flavors)) ['chocolate', 'bread', 'vanilla', 'cherry']
['lemon', 'chocolate', 'bread', 'vanilla', 'cherry']
There are 5 flavors in my list.
lemon chocolate bread vanilla cherry
This is all I have: 'lemon', 'chocolate', 'bread', 'vanilla', 'cherry'
This is all I have: lemon, chocolate, vanilla, cherry
Tupel¶
A tuple represents a collection of Python objects, similar to a list, and the sequence of values (data types) in a tuple can take any type. Elements of a tuple are also indexed with integers. In contrast to lists, a tuple is embraced with round parentheses () and a tuple is immutable while lists are mutable. This means that a tuple object can no longer be modified after it has been created. So why would you like to use tuples then? The answer is that a tuple is more memory efficient than a mutable object because the immutable tuple can create references to existing objects. In addition, a tuple can serve as a key of a dictionary (see below), which is not possible with a list.
a_tuple = ("a text element", 1, 3.03) # example tuple
print(a_tuple[0])
print(a_tuple[-1]) # last element of a tuple (this also works with lists ..)
# comparison of lists and tuples
import time # we need this package (module here) and we will learn more about modules later
print("patience ...")
# iterate over a list with 100000 elements
start_time = time.perf_counter()
a_list = [] # empty list
x = range(100000)
for item in x: a_list.append(item)
print("Run time with list: " + str(time.perf_counter() - start_time) + " seconds.")
# iterate over a tuple with 100000 elements with modifying the tuple
start_time = time.perf_counter()
new_tuple = () # empty tuple
x = range(100000)
for item in x: new_tuple = new_tuple + (item,)
print("Run time with tuple modification: " + str(time.perf_counter() - start_time) + " seconds.")
# iterate over a tuple with 100000 elements if no modification of the tuple is needed
start_time = time.perf_counter()
new_tuple = tuple(range(100000))
for item in new_tuple: pass
print("Run time without tuple modification: " + str(time.perf_counter() - start_time) + " seconds.")a text element
3.03
patience ...
Run time with list: 0.011113214000033622 seconds.
Run time with tuple modification: 12.448654852999425 seconds.
Run time without tuple modification: 0.006154237000373541 seconds.
Wörterbuch¶
Dictionaries are a powerful data type in Python and have the basic structure my_dict = {key: value}. In contrast to lists, an element of a dictionary is called by invoking a key rather than an entry number. A dictionary is not enumerated and keys just point to their values (whatever data type the value is).
my_dict = {1: "Value 1", 2: "Value 2"}
another_dict = {"list1": [1, 2, 3], "number2": 1}
my_dict [1]'Value 1'Auch Wörterbücher haben viele nützliche eingebaute Funktionen:
my_dict.update({3: "Value 3"}) # add a dictionary element
my_dict
del my_dict[1] # delete a dictionary element
len(my_dict) # get the length (number of dictionary elements)2Darüber hinaus können zwei Listen gleicher Länge in ein Wörterbuch gepflückt werden:
weight = [0.5, 1.0, 1.5, 2.0]
price = [1, 1.5, 1.8, 2.0]
apple_weight_price = dict(zip(weight, price))
print("{0} kg apples cost EUR {1}.".format(weight[2], apple_weight_price[weight[2]]))1.5 kg apples cost EUR 1.8.
Sätze¶
Ein Python-Set ist ein veränderliches Objekt, das mit lockigen Klammern instanziiert wird. Mengen sind ungeordnet (im Gegensatz zu Listen und Tupeln) und daher nützlich für mathematische Operationen wie Vereinigung, Schnittpunkt, Differenz oder symmetrische Differenz von Mengen von Elementen. Der folgende Codeblock zeigt die Instanziation von zwei Sätzen und die Anwendung von mathematischen Operatoren.
ice_shop_a = {"vanilla", "chocolate", "green"}
ice_shop_b = {"blue", "chocolate", "vanilla"}
print("Ice shops united: " + str(ice_shop_a | ice_shop_b))
print("Both shops offer in common: " + str(ice_shop_a & ice_shop_b))
print("This is what shop a has, but not shop b: " + str(ice_shop_a - ice_shop_b))
print("This is what shop b has, but not shop a: " + str(ice_shop_b.difference(ice_shop_a)))
print("This is what is unique to both shops (symmetric difference): " + str(ice_shop_a ^ ice_shop_b))Ice shops united: {'green', 'vanilla', 'chocolate', 'blue'}
Both shops offer in common: {'vanilla', 'chocolate'}
This is what shop a has, but not shop b: {'green'}
This is what shop b has, but not shop a: {'blue'}
This is what is unique to both shops (symmetric difference): {'green', 'blue'}
Betreiber¶
Die folgenden Operatoren vergleichen Datentypen und geben boolesche Werte aus (Trueoder False):
a == ba gleich b (gleicher Wert)a is ba ist b (das gleiche Objekt im Speicher - ein strengerer Test als==)a and ba und ba or ba oder ba <= ba kleiner oder gleich b (ähnlich ohne Gleichheitszeichen)a >= ba größer oder gleich b (ähnlich ohne Gleichheitszeichen)a in ba in b (z. B. Mitgliedschaftstest in einer Zeichenfolge oder Liste - siehe Beispiel unten)
print(not False)
print(1 == 1) # value equality
print(1 == 2)
print("ice" in "ice cream") True
True
False
True
Learning Success Check-up¶
Machen Sie den Lernerfolgstest für dieses Jupyter-Notebook].
Unfold QR Code
