How to Define a Function in Python?

This post is lesson 14 of 54 in the subject Python Programming Language

1. Definition of a Function in Python

A function in Python is a named block of code that takes input and produces output. The function solves a specific problem for the main program. The function can be called multiple times with different parameters.

Define a function in python
Define a function in python

Example:

def welcomeGochocit():
  print("Hi all, Welcome to Gochocit.com!")

welcomeGochocit()

Result

Hi all, Welcome to Gochocit.com!

2. Building and Calling a Function in Python

The syntax for building a function in Python:

def function_name(parameters):
    """docstring"""
    statement(s)
    return expression
  1. Use the def keyword to declare and define a function.
  2. function_name is the name of the function. Function names follow the rules for naming identifiers.
  3. parameters are input values that are passed into a function. These parameters are not always required, and may or may not be present.
  4. The end of the function declaration line is the colon (:).
  5. The function body starts with indentation.
  6. You can use docstring to describe the function’s functionality. The docstring in the function body may or may not exist.
  7. Within the function body, there may be many statements. Each statement starts with an indentation.
  8. A function may return a value with the return statement. But not all functions necessarily have a return statement.
def sum(a, b):
    """Plus a and b"""
    c = a + b
    return c

In the example above, the function name is sum with parameters a and b. The docstring is “””Plus a and b”””. This sum function is simple, so it only has one line of code which is c = a + b. The function returns a value with the statement return c.

Calling a Function in Python

To call a function, we just need to use the function name and pass the appropriate parameters.

def sum(a, b):
    """Plus a and b"""
    c = a + b
    return c

num1 = 1
num2 = 9
s = sum(num1, num2)
print("sum = ", s)

Result

sum =  10

Note: Functions must always be defined before calling them, otherwise an error will occur.

Example:

hello()

def hello():
    print("Hello all!")

Result

NameError: name 'hello' is not defined.

3. Return the Type of a Function in Python

The return statement helps to return one or more values from the function. Example:

def myFunction1():
    val = 5.9
    return val
a  = myFunction1()
print("#Result of myFunction1")
print("a = ", a)

def myFunction2():
    a = list(range(0, 5))
    b = 10
    return a, b, 9
x, y, z = myFunction2()
print("#Result of myFunction2")
print("x = ", x)
print("y = ", y)
print("z = ", z)

Result

#Result of myFunction1
a =  5.9
#Result of myFunction2
x =  [0, 1, 2, 3, 4]
y =  10
z =  9

In the above example, we see that a function can return multiple values with the return statement. Each value is separated by a comma (,).

In some cases, the return statement is used to exit the function. Example:

def absoluteFunction(num):
    """This function returns the absolute
    value of the entered number"""
    if num >= 0:
        return num
    else:
        return -num
print("#Result of absoluteFunction")
print(absoluteFunction(1))
print(absoluteFunction(-5))

def myFunction(num):
    if(num<=0):
        print("num must be greater than 0")
        return
    num = num * 5
    print(num)
print("#Result of myFunction with num > 0")
myFunction(9)
print("#Result of myFunction with num <= 0")
myFunction(-1)

Result

#Result of absoluteFunction
1
5
#Result of myFunction with num > 0
45
#Result of myFunction with num <= 0
num must be greater than 0

In the above example, the absoluteFunction function has a return statement that both return a value to the function and exits the function. The myFunction function has a return statement that only exits the function without returning a value to the function.

4. Nested Functions in Python

Python allows you to define a function inside another function. We call them inner functions or nested functions. Example:

def outerFunction(year):
    name = 'Gochocit.com'
    msg = 'Happy New Year'
    #define an inner function
    def innerFunction():
        print(name, ", ", msg, ' ', year, ' to everyone!', sep='')
    #call inner function
    innerFunction()

y = 2022
outerFunction(y)

Result

Gochocit.com, Happy New Year 2022 to everyone!

Inner functions can access variables in the outer function.

Rate this post
Previous and next lesson in subject<< Loops in Python: Using the break, continue, and pass statementsParameters of a function in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *