Functions are defined using the def statement.
They are called using the function name followed by parentheses,
with any arguments inside the parentheses.
>>> def double(x): ... print x * 2 ... >>> double(3) 6
A value can be returned from a function by the return statement.
>>> def factorial(n): ... if n > 0: ... return n * factorial(n-1) ... else: ... return 1 ... >>> x = factorial(5) >>> print x 120
By default, variables that are assigned to in a function only exist within
that function.
i.e. they have local scope.
The global statement is used to declare that a variable
should exist in the global scope.
This will make it visible outside of the function, after the function has
been called.
>>> def foo(a): ... y = a ... print y ... >>> foo(7) 7 >>> print y Traceback (most recent call last): File "", line 1, in ? NameError: name 'y' is not defined >>> def foo(a): ... global y ... y = a ... print y ... >>> foo(12) 12 >>> print y 12