USER-DEFINED FUNCTIONS IN PYTHON
Python provides built-in functions and also enables you to define your own functions. You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
- Function blocks begin with the keyword def followed by the function name and parentheses.
- Any input arguments should be placed within these parentheses.
- The first statement of a function can be an optional statement—the documentation string of the function or docstring.
- The code block within every function starts with a colon (:) and is indented.
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
- If a function does not specify return statement, the function automatically returns None, which is a special type of value in Python.
A very simple custom Python function is here:
>>> def func(): ... print 3 ... >>> func() 3
The preceding function is trivial, but it does illustrate the syntax for defining custom functions in Python. The following example is slightly more useful:
>>> def func(x): ... for i in range(0,x): ... print(i) ... >>> func(5) 0 1 2 3 4