Does Python have a function

Python course

Previous chapter: Dictionaries
Next chapter: Parameter transfer

Functions

syntax

Functions are introduced with the keyword def

def function-name (parameter list): instruction (s) The parameter list consists of one or more identifiers, separated by commas.
Parameters can be mandatory and optional. The optional parameters (0 or more) follow the mandatory ones.
Example: #! / Usr / bin / python def add (x, y): "" "Return x plus y." "" Return x + y print add (2, 3) The above function is called in the following interactive session : >>> execfile ("function1.py") 5 >>> add (4,5) 9 >>> add (8,3) 11 >>>

Example of a function with optional parameters

#! / usr / bin / python def add (x, y = 5): "" "Return x plus y." "" return x + y print add (2, 3) Calls to the functions could look like this:> >> execfile ("function1.py") 5 >>> add (4) 9 >>> add (8,3) 11 >>>

Docstring

The first statement of a function body is usually a character string that can be queried as the function name .__ doc__.
This instruction will Docstring called.
Example:

>>> execfile ("function1.py") >>> add .__ doc__ 'Return x plus y.' >>> add2 .__ doc__ 'Return x plus y. Y optional '>>>

Keyword parameters

This is an alternative way of calling up a function. The function definition itself does not change.
An example:

def sumsub (a, b, c = 0, d = 0): return a - b + c - d Only those keyword parameters may be used that have not already been used as position arguments. >>> execfile ("function1.py") >>> sumsub (12,4) 8 >>> sumsub (12,4,27,23) 12 >>> sumsub (12,4, d = 27, c = 23) 4

Any number of parameters

There are very often cases in which the number of parameters required for the call is not known a priori. You can do this in Python using a so-called tuple reference. The last parameter is preceded by an *, which should not be confused with the corresponding C syntax.
Example:

def any (x, y, * more): print "x =", x, ", x =", y print "more:", more x and y are two common (position) parameters in the above function. The asterisk in front of the third parameter * more references a tuple.
Example: >>> execfile ("function1.py") >>> any (3,4) x = 3, x = 4 more: () >>> any (3,4, "hello world", 3, 4 ) x = 3, x = 4 more: ('Hello world', 3, 4)
Previous chapter: Dictionaries
Next chapter: Parameter transfer