...

/

Functions in Python

Functions in Python

Learn to create user-defined functions in Python.

What is a function?

A function is a piece of code that runs only when it’s called. We can input data as parameters to a function. We can also get data as output from a function. Our programs extensively use built-in Python functions. Some examples of built-in functions include range(), len(), round(), and print().

We can also define custom functions known as user-defined functions. In this lesson, we discuss how to create and use user-defined functions.

User-defined functions

The syntax for creating a user-defined Python function is given below.

def function_name(parameters):
  statement(s)
  return expression
Syntax of a Python function

Python uses the keyword def to define a function followed by the function name. The parameters are input to the function. When we pass real values to a function, they’re called function arguments. A function:

  • Might not have any parameter as an input.

  • Runs one or more statement(s) and returns the output data as an expression.

  • Might not have a return statement.

  • Might return single or multiple outputs separated by ...