print("Hello World!") # kein Rückgabewert (None)
Hello World!
Die Funktion print
gibt Werte am Bildschirm aus:
help(print)
print("Hello World!") # kein Rückgabewert (None)
Hello World!
Die Funktion str
erstellt ein String-Objekt:
help(str)
str(59) # Rückgabewert '59' (str)
'59'
Die Funktion int
erstellt ein Integer-Objekt:
help(int)
int("59") # Rückgabewert 59 (int)
59
Die Funktion max
gibt das Maximum der Argumente zurück:
help(max)
max(54, -12, 33, -100, -2) # Rückgabewert -100 (int)
54
Die Funktion sum
gibt die Summe einer Sequenz (z.B. Liste an Zahlen) zurück:
help(sum)
sum([1, 2, 3, 4]) # Rückgabewert 10 (int)
10
def mult(a, b):
"""Multiply a and b."""
return a * b
1, 1) # 1 mult(
1
2, 6) # 12 mult(
12
-12, 36) # -432 mult(
-432
def to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return celsius * 9/5 + 32
def to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
0) to_fahrenheit(
32.0
20) to_fahrenheit(
68.0
38) to_fahrenheit(
100.4
100) to_fahrenheit(
212.0
32) to_celsius(
0.0
68) to_celsius(
20.0
100.4) to_celsius(
38.0
212) to_celsius(
100.0
0)) to_celsius(to_fahrenheit(
0.0
20)) to_celsius(to_fahrenheit(
20.0
38)) to_celsius(to_fahrenheit(
38.0
100)) to_celsius(to_fahrenheit(
100.0
Funktionen
Eine Funktion muss definiert sein, bevor man sie benutzen (aufrufen) kann. Durch die Definition weiß Python, welcher Code dann beim Aufruf ausgeführt werden muss.
Erst beim Aufrufen der Funktion wird der Code im Funktionskörper tatsächlich ausgeführt. Für alle Parameter werden dann die tatsächlich übergebenen Werte (die Argumente) verwendet.
Eine Funktion kann bei der Definition Parameter haben. Beim Aufruf einer Funktion übergibt man dann für die Parameter tatsächliche Werte, welche man Argumente nennt.
def nonsense(a, b=10, c=13):
return a**2 - b * 2 + c**2
# TypeError, da a=undefiniert, b=10, c=13 nonsense()
TypeError: nonsense() missing 1 required positional argument: 'a'
22, 15, 78) # 6538; a=22, b=15, c=78 nonsense(
6538
11, 3) # 284; a=11, b=3, c=13 nonsense(
284
=42) # 1913; a=42, b=10, c=13 nonsense(a
1913
=17, c=88) # 8013; a=17, b=10, c=88 nonsense(a
8013
3, 4, c=5) # 26; a=3, b=4, c=5 nonsense(
26
3, c=2) # -7; a=3, b=10, c=2 nonsense(
-7