Visit: https://a2zcareers.viden.io
In Python, a function is a group of related statements that performs 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 the code reusable.
def function_name(parameters): """docstring""" statement(s)
Above shown is a function definition that consists of the following components.
def
that marks the start of the function header.return
statement to return a value from the function.def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!")
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
>>> greet('Paul') Hello, Paul. Good morning!
Note: Try running the above code in the Python program with the function definition to see the output.
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") greet('Paul')
Output:
Hello, Paul. Good morning!
The first string after the function header is called the docstring and is short for documentation string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
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 the __doc__
attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__) This function greets to the person passed in as a parameter
To learn more about docstrings in Python, visit Python Docstrings.
The return
statement is used to exit a function and go back to the place from where it was called.
return [expression_list]
This statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return
statement itself is not present inside a function, then the function will return the None
object.
For example:
>>> print(greet("May")) Hello, May. Good morning! None