Python Data Persistence – User Defined Functions
As mentioned earlier, it is possible to define a custom function if you don’t find a suitable one in the collection of predefined functions. It is popularly called a user-defined function. So, let us proceed to define a new function and learn how to use it.
Python provides a def keyword for this purpose. This keyword is followed by a suitable identifier and in front of which give parentheses. The parentheses may or may not have anything inside. This is followed by a function block of one or more statements of uniform indent level. A formal outline of function definition appears like this:
#defining a function def function ( [ p1 , p2 , . . ] ) : ' function docstring as first-line in function block' . . . . return [value]
Subsequent lines can have any number of valid Python statements as demanded by the function’s processing logic. The last statement of the block should be returned indicating that the program’s control is going back to the position from where this function was called. You may put an expression in its front if it is required that this function should not just return but return with a value (most of the time, result of the function).As always you’ll use the symbol to start a block. You may write a string literal as an explanatory string for the function. It is called docstring and is optional. Something similar to comment but is treated as the value of function’s _doc_ attribute.
How should this user-defined function be called? Just use its name as a Python statement anywhere in the code after it has been defined. Of course, you need to provide adequate parameters if the function’s definition contains any.
So, let us define a function with the name ‘zen’ and no parameters. When called, it will print a couple of lines from ‘Zen of Python’ – a set of guiding principles that govern the design philosophy of Python.
- Python Data Persistence – class Keyword
- how to call a function in python Guide
- Python Programming – Scope
#function-1.py def zen( ): ' Zen of Python ' print ( ' Beautiful is better than ugly. Explicit is better than implicit.') print ('Simple is better than complex. Complex is better than complicated.') return #call above function zen ( ) print ('Docstring:', zen. _doc_ )
E:\python37>python function-1.py Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. The complex is better than the complicated. Docstring: Zen of Python
Note that docstring – the first line in function block is not executed by interpreter but is recognized as the value of doc attribute.