Python Functions

This lesson will teach you about creating; calling a function in Python functions, including what a return declaration in the function is, with examples.

What is a Python Function?

Our program can be divided up into smaller, modular portions with the use of functions. In Python, a function is a collection of connected statements that work together to complete a certain goal. Functions enable our program to become more streamlined and controllable as it expands; Additionally, it keeps the code reusable and prevents repetition.

Creating a Function in Python

In Python, a function is defined by utilizing the def keyword:


def myFirstFunction():
print("Python Function")

The function definition above consists of the following elements.

  1. It begins with the keyword def in the function header.
  2. A name for the function that serves as a unique identifier. The conventions for creating Python identifiers apply to naming functions as well.
  3. We use the variables (arguments) to supply values to a function. They are not required.
  4. The function header ends with a colon (:).
  5. The function’s body is composed of one or more legitimate Python statements. The indentation level for each statement must be the same (usually 4 spaces).
  6. An optional return statement allows the function to return a value.

Calling a Function in Python

Use the function name in parenthesis to invoke the function. After defining a function, we can use it to call other functions, programs, or even the Python prompt. Simple typing of the function name and the compiler will invoke the function.


def myFirstFunction():
print("Python Function")


Python Function
In Python, the function definition must always come first. If not, we will encounter an error.

For illustration

def myFirstFunction():
print("Python Function")


Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'myFirstFunction' is not defined

Return declaration of Function in Python

Use the return statement to allow a function to return a value. To leave a function and return to where it was called, utilize the return statement.

Basic syntax

[return statement]

The value is returned once the expression in this statement has been evaluated. The function will return the no object if there is no expression in the statement or if the return statement itself is missing from a function.

For instance

def myFirstFunction(x):
sum =2 + x
return sum



Here, 5 is the returned value since myFirstFunction() return the sum and prints it while calling.