#!/usr/bin/python3
def F0():
print ('in F0')
F0()
# in F0
# The function needs to be called with the
# paranthesis: The following line does not
# invoke the function.
F0
#!/usr/bin/python3
def F_args(a, b, c):
print('' )
print(' a = ' + str(a))
print(' b = ' + str(b))
print(' c = ' + str(c))
F_args('foo', 'bar', 'baz')
#
# a = foo
# b = bar
# c = baz
# Any type can be passed to the function …
# … but in order to print them, the function
# needs to call str()
F_args( 1 , 2 , 3 )
#
# a = 1
# b = 2
# c = 3
#!/usr/bin/python3
def F_named_args(a, b, c = 'FOO', d = 'BAR', e = 'BAZ'):
print('' )
print(' a = ' + str(a))
print(' b = ' + str(b))
print(' c = ' + str(c))
print(' d = ' + str(d))
print(' e = ' + str(e))
# --------------------------
#
# Normal call
#
F_named_args('one', 'two')
#
# a = one
# b = two
# c = FOO
# d = BAR
# e = BAZ
# -------------------------------
#
# Explicitely pass a value for a
# key-argument:
#
F_named_args('one', 'two', d='DDD')
#
# a = one
# b = two
# c = FOO
# d = DDD
# e = BAZ
# -------------------------------
#
# Positional arguments can
# be named, too:
#
F_named_args(b='BBB', a='AAA')
#
# a = AAA
# b = BBB
# c = FOO
# d = BAR
# e = BAZ
Similarly, an argument can be declared with two prefixing stars. In that case, the function expects there to be passed any number of named arguments. The type of the argument within the function is a dict.
#!/usr/bin/python3
def two_stars(a, **b):
print('')
print(' a = ' + str(a))
print(' type(b) = ' + str(type(b)))
for k,v in b.items():
print(' ' + k + ' = ' + str(v))
two_stars('foo')
#
# a = foo
# type(b) = <class 'dict'>
#
two_stars('bar', num = 42)
#
# a = bar
# type(b) = <class 'dict'>
# num = 42
two_stars('baz', x = 'eggs', y = 'why')
#
# a = baz
# type(b) = <class 'dict'>
# x = eggs
# y = why
When a function is called, a namespace is created.
This namespace is destroyed when the function is exited.
When functions are called recursively, each function invocation gets its own namespace.
docstring
If a function's first statement is just a string literal, the value of this string becomes the function's docstring and can be queried on the function object's __doc__ attribute.
def F():
'This is the functions docstring'
return 4
def G(a):
"""\
This docstring demonstrates that
a docstring can also span
multiple lines."""
return a ** 2
print(F.__doc__)
print(G.__doc__)
The def statement inserts the function name in the current symbol table.
TODO
In order to create a generator function, the function definition must have a yield statement - and this is also sufficient to create such a generator function.