Übung 6 – Datentypen und f-Strings
Ziel dieser Übung
Sie unterscheiden die Datentypen int, float und str und setzen Werte mit f-Strings bequem in Texte ein.
Tipp: Jeder Code lässt sich mit „Kopieren“ übernehmen. Zum Lernen ist es aber besser, ihn selbst abzutippen – so üben Sie Schreibweise und Umgang mit dem Terminal.
1. Warum Datentypen wichtig sind
Was der Operator + macht, hängt davon ab, womit er arbeitet. Zwei Texte werden verbunden:
text1 = "Hallo"
text2 = "Welt"
print(text1 + text2)
HalloWelt
Zwei Zahlen werden addiert:
zahl1 = 10
zahl2 = 3
print(zahl1 + zahl2)
13
Mischen Sie Zahl und Text, bricht Python mit einem Fehler ab:
print(5 + "fünf")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
2. Drei grundlegende Datentypen
| Datentyp | Bedeutung | Beispiel |
|---|
int | ganze Zahl (integer) | alter = 36 |
float | Kommazahl (floating point) – mit Punkt | preis = 2.5 |
str | Text (string) – in Anführungszeichen | name = "Ada" |
Mit type() fragen Sie Python nach dem Datentyp eines Werts:
print(type(36))
print(type(2.5))
print(type("Ada"))
print(type("36"))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
Achtung: "36" in Anführungszeichen ist Text, keine Zahl – auch wenn nur Ziffern darin stehen.
3. f-Strings: Werte in Text einsetzen
Ohne f-String müssen Sie Text und Zahlen mühsam zusammenstückeln – und Zahlen vorher mit str() in Text umwandeln:
name = "Ada"
alter = 36
print("Ich heiße " + name + " und bin " + str(alter) + " Jahre alt.")
Ich heiße Ada und bin 36 Jahre alt.
Mit einem f-String geht das viel einfacher: ein f vor das Anführungszeichen, Variablen in geschweifte Klammern { }:
name = "Ada"
alter = 36
print(f"Ich heiße {name} und bin {alter} Jahre alt.")
Ich heiße Ada und bin 36 Jahre alt.
In den Klammern darf auch gerechnet werden:
preis = 2.5
anzahl = 4
print(f"{anzahl} Brezeln kosten {preis * anzahl} Euro.")
4 Brezeln kosten 10.0 Euro.
Mit drei Anführungszeichen geht es auch über mehrere Zeilen:
name = "Ada"
stadt = "Weingarten"
print(f"""Steckbrief
Name: {name}
Stadt: {stadt}""")
Steckbrief
Name: Ada
Stadt: Weingarten
4. Ein Beispiel mit allen drei Datentypen
Ein kleiner Rechner für den Preis eines Produkts mit Mehrwertsteuer:
produkt = "Buch" # str
grundpreis = 10.0 # float
mehrwertsteuer = 19 # int
endpreis = grundpreis + grundpreis * mehrwertsteuer / 100
print(f"Das {produkt} kostet inklusive {mehrwertsteuer} % Mehrwertsteuer {endpreis} Euro.")
Das Buch kostet inklusive 19 % Mehrwertsteuer 11.9 Euro.
Für Neugierige: Mit {endpreis:.2f} zeigt der f-String immer genau zwei Nachkommastellen – also 11.90.
Aufgabe 1 · Eine Nachricht ausgeben Übung
Speichern Sie Ihren Namen und Ihr Alter in zwei Variablen. Geben Sie mit einem f-String aus: „Mein Name ist … und ich bin … Jahre alt.“
Lösung anzeigen
name = "Alex"
alter = 21
print(f"Mein Name ist {name} und ich bin {alter} Jahre alt.")
Mein Name ist Alex und ich bin 21 Jahre alt.
Aufgabe 2 · Die Summe berechnen Übung
Speichern Sie zwei ganze Zahlen in Variablen und geben Sie ihre Summe in einem Satz aus. Erklären Sie mit Kommentaren (#), was jede Zeile macht.
Lösung anzeigen
# zwei ganze Zahlen speichern
zahl1 = 12
zahl2 = 30
# Summe berechnen und in einer neuen Variablen speichern
summe = zahl1 + zahl2
# Ergebnis als Satz ausgeben
print(f"Die Summe von {zahl1} und {zahl2} ist {summe}.")
Die Summe von 12 und 30 ist 42.
Aufgabe 3 · Texte verbinden Übung
Speichern Sie zwei Teile eines Satzes in zwei Variablen, z. B. "Hallo, mein Name ist " und "Max". Geben Sie den ganzen Satz einmal mit + und einmal mit einem f-String aus.
Lösung anzeigen
teil1 = "Hallo, mein Name ist "
teil2 = "Max"
print(teil1 + teil2)
print(f"{teil1}{teil2}")
Hallo, mein Name ist Max
Hallo, mein Name ist Max
Aufgabe 4 · Ein einfacher Währungsrechner Übung
- Legen Sie einen Betrag in Euro fest, z. B.
100. - Legen Sie für drei Währungen den Kurs fest: Wie viel bekommt man für 1 Euro? Schlagen Sie die aktuellen Kurse nach – sie ändern sich täglich.
- Rechnen Sie den Betrag in jede Währung um und geben Sie je einen Antwortsatz aus.
Lösung anzeigen
Die Kurse in der Lösung sind nur Beispielwerte, keine aktuellen Kurse.
betrag = 100 # Euro
# Beispielkurse: so viel gibt es für 1 Euro
kurs_usd = 1.15
kurs_gbp = 0.87
kurs_chf = 0.94
print(f"{betrag} Euro sind {betrag * kurs_usd} US-Dollar.")
print(f"{betrag} Euro sind {betrag * kurs_gbp} Britische Pfund.")
print(f"{betrag} Euro sind {betrag * kurs_chf} Schweizer Franken.")
100 Euro sind 114.99999999999999 US-Dollar.
100 Euro sind 87.0 Britische Pfund.
100 Euro sind 94.0 Schweizer Franken.
Überrascht von 114.99999999999999? Der Computer speichert Kommazahlen binär und kann 1.15 nicht ganz genau darstellen. Mit {betrag * kurs_usd:.2f} wird daraus 115.00.
Weiter zu Übung 7: Eingaben mit input() →
Exercise 6 – Data types and f-strings
Goal of this exercise
You distinguish the data types int, float and str and conveniently insert values into text with f-strings.
Tip: every code block can be copied with “Copy”. For learning, it is better to type it yourself – that is how you practise syntax and using the terminal.
1. Why data types matter
What the + operator does depends on what it works with. Two texts are joined:
text1 = "Hallo"
text2 = "Welt"
print(text1 + text2)
HalloWelt
Two numbers are added:
zahl1 = 10
zahl2 = 3
print(zahl1 + zahl2)
13
If you mix a number and text, Python stops with an error:
print(5 + "fünf")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
2. Three basic data types
| Data type | Meaning | Example |
|---|
int | whole number (integer) | alter = 36 |
float | decimal number (floating point) – with a point | preis = 2.5 |
str | text (string) – in quotation marks | name = "Ada" |
With type() you ask Python for the data type of a value:
print(type(36))
print(type(2.5))
print(type("Ada"))
print(type("36"))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
Note: "36" in quotation marks is text, not a number – even if it contains only digits.
3. f-strings: inserting values into text
Without an f-string you have to piece text and numbers together – and convert numbers to text with str() first:
name = "Ada"
alter = 36
print("Ich heiße " + name + " und bin " + str(alter) + " Jahre alt.")
Ich heiße Ada und bin 36 Jahre alt.
With an f-string it is much easier: an f before the quotation mark, variables in curly braces { }:
name = "Ada"
alter = 36
print(f"Ich heiße {name} und bin {alter} Jahre alt.")
Ich heiße Ada und bin 36 Jahre alt.
You can also calculate inside the braces:
preis = 2.5
anzahl = 4
print(f"{anzahl} Brezeln kosten {preis * anzahl} Euro.")
4 Brezeln kosten 10.0 Euro.
With three quotation marks it also works over several lines:
name = "Ada"
stadt = "Weingarten"
print(f"""Steckbrief
Name: {name}
Stadt: {stadt}""")
Steckbrief
Name: Ada
Stadt: Weingarten
4. An example with all three data types
A small calculator for the price of a product including VAT:
produkt = "Buch" # str
grundpreis = 10.0 # float
mehrwertsteuer = 19 # int
endpreis = grundpreis + grundpreis * mehrwertsteuer / 100
print(f"Das {produkt} kostet inklusive {mehrwertsteuer} % Mehrwertsteuer {endpreis} Euro.")
Das Buch kostet inklusive 19 % Mehrwertsteuer 11.9 Euro.
For the curious: with {endpreis:.2f} the f-string always shows exactly two decimal places – i.e. 11.90.
Task 1 · Print a message Practice
Store your name and your age in two variables. Use an f-string to print: “My name is … and I am … years old.”
Show solution
name = "Alex"
alter = 21
print(f"Mein Name ist {name} und ich bin {alter} Jahre alt.")
Mein Name ist Alex und ich bin 21 Jahre alt.
Task 2 · Calculate the sum Practice
Store two whole numbers in variables and print their sum in a sentence. Use comments (#) to explain what each line does.
Show solution
# zwei ganze Zahlen speichern
zahl1 = 12
zahl2 = 30
# Summe berechnen und in einer neuen Variablen speichern
summe = zahl1 + zahl2
# Ergebnis als Satz ausgeben
print(f"Die Summe von {zahl1} und {zahl2} ist {summe}.")
Die Summe von 12 und 30 ist 42.
Task 3 · Join texts Practice
Store two parts of a sentence in two variables, e.g. "Hallo, mein Name ist " and "Max". Print the whole sentence once with + and once with an f-string.
Show solution
teil1 = "Hallo, mein Name ist "
teil2 = "Max"
print(teil1 + teil2)
print(f"{teil1}{teil2}")
Hallo, mein Name ist Max
Hallo, mein Name ist Max
Task 4 · A simple currency converter Practice
- Set an amount in euros, e.g.
100. - Set the rate for three currencies: how much do you get for 1 euro? Look up the current rates – they change daily.
- Convert the amount into each currency and print one answer sentence each.
Show solution
The rates in the solution are only sample values, not current rates.
betrag = 100 # Euro
# Beispielkurse: so viel gibt es für 1 Euro
kurs_usd = 1.15
kurs_gbp = 0.87
kurs_chf = 0.94
print(f"{betrag} Euro sind {betrag * kurs_usd} US-Dollar.")
print(f"{betrag} Euro sind {betrag * kurs_gbp} Britische Pfund.")
print(f"{betrag} Euro sind {betrag * kurs_chf} Schweizer Franken.")
100 Euro sind 114.99999999999999 US-Dollar.
100 Euro sind 87.0 Britische Pfund.
100 Euro sind 94.0 Schweizer Franken.
Surprised by 114.99999999999999? The computer stores decimals in binary and cannot represent 1.15 exactly. With {betrag * kurs_usd:.2f} it becomes 115.00.
On to exercise 7: input with input() →