How to define a function in Python
A function is simply a container for a few lines of code that perform a simple task. All programming languages have functions as a common feature. Functions allow developers to write blocks of code that perform specific and reusable tasks. A function can be executed as many times as the developer wants throughout their code.
Functions in Python
In Python, there are two types of functions:
- Built-in functions
- User-defined functions
Built-in functions are those functions pre-installed in Python. Examples include:
print(): to print an object to the terminal.help(): to ask for help.min(): to get the minimum value.
User-defined functions are those functions defined by the user. Examples include:
def greet_customer()def calculate()def take_square()
They all are defined by the user to help them perform certain tasks when writing a program.
How to define a function
Defining a function in Python simply means to create a function. Functions in Python are created and denoted using the keyword def, followed by a function name. For example, greet_user followed by a set of parenthesis().
When a function is defined, every letter of the function must be in lowercase.
Example
Let’s create a simple function that helps us greet a customer. The function will return the following statements:
Hellowelcome aboard to the home of delicacies
Code
# defining a funtion that will greet a customerdef greet_customer():print('Hello')print('welcome aboard to the home of delicacies')# calling the functiongreet_customer()
Explanation
-
In the code above, we used the
defkeyword to show that we are defining a function. -
The name of our function is
greet_customer(). The parenthesis()are where the parameters of the functions are stored. The double line breaks must be included after defining a function. -
The
greet_custumer()function is used to called the key function. Without calling the key function, the program will not execute the defined function.