Python Functions
In Python, a function is a group of related statements that performs a specific task.
What is a function in Python?
Functions allow you to define reusable blocks of code in a program.
Functions can be called, receive values for use in code within them, and return values.
Functions help to break down the program into smaller, modular parts. This is very important when the program becomes very large and it is essential to keep it organized and maintainable.
Syntax
The syntax for defining a Python function is:
def function_name(arguments):
"""docstring"""
statement
statement
...
return value
where:
- Keyword
def
marks the beginning of the function header. - The
function_name
is an identifier by which the function is called. It uniquely identifies the function. arguments
contains a list of values passed to the function.- A colon
:
marks the end of the function header and all subsequent statements must be indented to form the body of the function. - Optional documentation string (docstring) can be added to describe how the function works.
- An optional
return
statement is used to return one or more values from the function.