Python: Function

Functions enable us to isolate and encapsulate a certain piece of code into its own block. And then it can be used in different places of the program without repeating the same code over and over again.

NOTES

In Python, functions are first-class objects(entities), so a function can be-

Assigned to variables.
Stored in data structures like- list, dictionary, tuple, etc.
Passed to another function as an argument.
Returned from other functions.
Wrapped into other functions.
Created dynamically at runtime.
Have attributes assigned to them.

Let’s see how we can define a function, and how the functions can be used in different use cases.

WARNING

In this article, we are discussing how to define and use custom(used defined) functions.

Built-in Python functions are not discussed here, in this article.

Define Function

Function definition starts with the “def” keyword.
After “def” comes the function name. We can use any valid function name here.
After the function name, we need parenthesis.
At the end of the definition line, we put a colon(:).
Then we write the definition of the function. All the code that needs to be executed for that functionality should be here.
def your_function_name_here():
    # Indentation before the code(for full section) is required
    
    # code for execution
    # Whatever functionality we want to implement shold be here
    
    x = 100
    print(x)
    
    
    
    
    
    
# Call the function like below
your_function_name_here()
Python
After the function name, we have the parameters wrapped inside the parenthesis. Parameters are optional, so in case there is no parameter, we can leave the parenthesis blank.
def your_function_name_here(param1, param2):
    # code for execution
    # Whatever functionality we want to implement shold be here
    
    # Indentation before the code(for full section) is required
    
    
# Call the function like below
your_function_name_here(100, 200)
Python
We can also define a return value at the end of the function.
If there is a return type then we can get that from the function call, and save it in a variable.
def your_function_name_here(param1, param2):
    # code for execution
    # Whatever functionality we want to implement shold be here
    
    # Indentation before the code(for full section) is required
    
    return param1 + param2
    
    
# Call the function like below
result = your_function_name_here(100, 200)
Python

Examples

Let’s start with a simple function definition and usage-

# Define a function
def big_box_func():
    print("running function big_box_func")
    
# Call and execute the function    
big_box_func()
Python

Output:

running function big_box_func
Plaintext

Required Parameters

def sum(num1, num2):
    return num1 + num2

result = sum()
print("Result of the sum: ",  result)
Python

Output:

Traceback (most recent call last):
  File "bigboxcode.py", line 11, in <module>
    result = sum()
             ^^^^^
TypeError: sum() missing 2 required positional arguments: 'num1' and 'num2'
Plaintext

Optional Parameters

def big_box_number_printer(limit=5):
    for i in range(limit):
        print(i)
        
big_box_number_printer(2)
big_box_number_printer()
Python

Output:

0
1

0
1
2
3
4
Plaintext

Return Value

We can return some value at any point of the function. The return value can be received by assigning the function call to a variable.

WARNING

The function immediately stops executing further, when it reaches a return statement.

Depending on our implementation a function may or may not return any value-

When a function does not return a value we call it a “void” function. (we also call it a “not fruitful” function).
When a function returns a value we call it a “fruitful” function.

Case #1: General return Statement

def my_custom_func(num1, num2):
    if num1 < 100:
        return num1
    if num2 < 100:
        return num2
    
    return num1 + num2

result = my_custom_func(20, 50)
print("Result of the my_custom_func(20, 50): ",  result)

result = my_custom_func(200, 50)
print("Result of the my_custom_func(200, 50): ",  result)

result = my_custom_func(200, 500)
print("Result of the my_custom_func(200, 500): ",  result)
Python

Output:

Result of the my_custom_func(20, 50):  20
Result of the my_custom_func(200, 50):  50
Result of the my_custom_func(200, 500):  700
Plaintext

Case #2: Empty return Statement

We can just type “return” as a return value, in that case, it will return “None”. Check the code below-

def my_custom_func():
    # Perform some operations
    
    # Just use return without any value
    return

result = my_custom_func()
print("Result of the my_custom_func(): ",  result)
print("Type of the result: ",  type(result))
Python

Output:

Result of the my_custom_func():  None
Type of the result:  <class 'NoneType'>
Plaintext

Case #3: No return Statement

A function can have no return statement, when we don’t need to return anything. In that case we will receive a ‘None’ if we try to get the result of the function-

def my_custom_func():
    # Perform some operations

    print("inside my_custom_func")


result = my_custom_func()
print("Result of the my_custom_func(): ",  result)
print("Type of the result: ",  type(result))
Python

Output:

Result of the my_custom_func():  None
Type of the result:  <class 'NoneType'>
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.