An Example

[9]:
def maximum(a, b):
    if a < b:
        return b
    else:
        return a
[11]:
maximum(42, 666)
[11]:
666
[13]:
maximum(42, 666) / 2
[13]:
333.0
[14]:
m = maximum(42, 666) / 2
[15]:
m
[15]:
333.0

Sidenote: Pure Beauty

[16]:
type(maximum)
[16]:
function
[17]:
maximum(42, 666)
[17]:
666
[18]:
a = maximum
a(42, 666)
[18]:
666

Parameters and Types

Aufruf mit int ist ok:

[20]:
maximum(42, 666)
[20]:
666

Aufruf mit int und float auch:

[22]:
maximum(42, 6.666)
[22]:
42
[24]:
try:
    maximum(42, '666')
except Exception as e:
    print(e)
'<' not supported between instances of 'int' and 'str'
[25]:
maximum(42, int('666'))
[25]:
666
[28]:
try:
    maximum(42, int('xxx'))
except Exception as e:
    print(e)
invalid literal for int() with base 10: 'xxx'

Default Parameters

[34]:
def say_hello(name, greeting):
    print(f'{greeting}, {name}')   # f-String, since Python 3.6
    # print(greeting + ', ' + name)
[35]:
say_hello('Jörg', 'Seas')
Seas, Jörg
[37]:
def say_hello(name, greeting='Hello'):
    print(f'{greeting}, {name}')   # f-String, since Python 3.6
[38]:
say_hello('Jörg')
Hello, Jörg

Pitfalls

[48]:
def f(i, x=[]):
    x.append(i)
    return x
[49]:
f(1)
[49]:
[1]
[47]:
f(2)
[47]:
[1, 2]

Keyword Arguments

[50]:
def velocity(length_m, time_s):
    return length_m / time_s
[52]:
velocity(100, 3)
[52]:
33.333333333333336
[55]:
velocity(3, 100)
[55]:
0.03
[57]:
velocity(time_s = 3, length_m = 100)
[57]:
33.333333333333336