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:

  • Hello
  • welcome aboard to the home of delicacies

Code

# defining a funtion that will greet a customer
def greet_customer():
print('Hello')
print('welcome aboard to the home of delicacies')
# calling the function
greet_customer()

Explanation

  • In the code above, we used the def keyword 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources