Function Definition
What is a Function?
In Python, a function is a block of organized, reusable code that is used to perform a specific action. It provides better modularity for your application and promotes code reusability.
How to Define a Function?
Functions in Python are defined using the def
keyword, followed by a function name and parentheses (()
). Any input parameters should be placed within these parentheses, and the function’s body is indented under the function definition. The syntax is as follows:
Here, function_name
is the name of the function, parameter1
and parameter2
are parameters which are inputs to your function, and pass
is a Python statement that does nothing. It can be used when a statement is required syntactically but the function does not need to execute any code.
For instance, let’s create a simple function that greets anyone based on the name passed as a parameter:
Running this code prints "Hello, Alice. Nice to meet you!"
.
Note
You can pass as many parameters as you want into a function by separating them with commas.
Docstrings
Docstrings, also known as documentation strings, are descriptive text strings enclosed with triple quotes (""" ... """
). They provide a way of commenting Python functions, methods, modules and classes. A docstring is associated with the object as their __doc__
attribute. For functions, the docstring is a line that comes immediately after the function definition, and is used for explaining what the function does.
This would print:
Docstrings are a good programming practice, as they make your code more readable and accessible for other developers or even your future self.