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:
1def function_name(parameter1, parameter2):
2 # statements to be executed within the function
3 pass
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:
1def greet(name):
2 print(f"Hello, {name}. Nice to meet you!")
3
4# Now, we can call our function:
5greet("Alice")
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.
1def greet(name):
2 """
3 This function greets a
4 person passed in as a parameter
5 """
6 print(f"Hello, {name}. Nice to meet you!")
7
8# We can access the docstring using the __doc__ attribute
9print(greet.__doc__)
This would print:
This function greets a
person passed in as a parameter
Docstrings are a good programming practice, as they make your code more readable and accessible for other developers or even your future self.