What is a function in Python?
In Python, a function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
“””docstring”””
statement(s)
The above shown is a function definition that consists of the following components.
1.Keyword def marks the start of the function header.
2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
3.Parameters (arguments) through which we pass values to a function. Parameters are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6.One or more valid python statements that make up the function body. Statements must have the same indentation level.
7.An optional return statement to return a value from the function.
Example of a function
Example:1:
def hello(): print("hello function") print("how are you") def good(): print("this is good function") #function calling hello() good()
output:
hello function
how are you
this is good function
Docstring
The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function.
For example:
def hello(): """ this is just to test a function """ print("hello function") print("how are you") def hi(): ''' this is function hi to test function ''' print("this is good function") #function calling print("to call a function ") hello() hi() print() print() print("printinf doc string") print(hello.__doc__) print(hi.__doc__)
output:
to call a function
hello function
how are you
this is good function
printing doc string
this is just to test a function
this is function hi
to test function