How to call function in python – how to call a function in python Guide

How to call function in python: In this article, we will know how to call a function in Python.  You should have Python installed in your machine. You should know the basics of  Python syntax.  if you don’t check our installation guide and get started guide.

Content

  • How to create a function in Python
  • What are the scopes in Python
  • How to call a function in python

In a previous article, we talked more about Python and how it supports many paradigms. One of these Paradigms is a function. The functional programming paradigm is one of the most popular paradigms. Many languages support this paradigm. The functional paradigm in a nutshell is isolating logic into functions. You can call these functions anywhere. What are the benefits of this paradigm?

It helps the code to be easy to read and maintain. Each function performs a single job. This makes it easy to reuse the different functions in different places in the code. It helps to maintain and change business logic easily without the need to refactor the whole code.

How to create a function in Python

Calling a function in python: Defining a function in Python can be done by adding the def keyword. Python will know that this logic will be inside this function. The variables will be accessible inside the function only. This called scope. we will talk more about it in the next section. Let’s define a function.

def func_name():
    """
    Here is a docstring for the fucntion.
    """
    return True

The above code describes how to define a function in Python. It has the def keyword to tell Python that the next name is a function name. The next part is func_name()the name of the function. It has brackets to accept arguments you need to pass it to this function. The docstring part is a free text area that explains what this function is doing. The final part is the return keyword. It has the value you need to return from the function.

The above was a very simple example of a function. Let’s try to start with more complex examples.

def sum_static():
    return 1 + 2

def sum_dynamic(x, y):
    return x + y

def welcome_msg(name):
    welcome_text = "Dear {name} welcome to our guide to python functions".format(name=name)
    return welcome_text

def check_type(number):
    """
    Function that detrimine the type of integer
    """
    if not isinstance(number, int):
        return "Invalid number"
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

def dictify(key, value):
    """
    Return a dict {key: value}
    """
    data = dict()
    data[str(key)] = value
    return data

In the above, we have a couple of functions with different usage and complexity. Le’s explain them.

In the first sun_static function, it’s a static function that doesn’t take any parameters. It will always return the summation of 1 and 2. Python functions can accept parameters. The goal of these parameters is to make Python functions dynamic. In the second sum_dynamic accept two parameters x and y. If you passed them to the function it’ll add them and return the result. The Third function has more complicated logic it’ll return a welcome message with the name argument. In this function, we defined a variable welcome_text. This variable is only in the scope of this function. We need to know more about scopes in Python.

What is the scope in Python?

The scope or it can be called a namespace in Python is the area of this variable effect. In a more simple way. It’s the space that if you called this variable it’ll be valid. This means that the variable defined inside the functions is accessible only inside the function. If you tried to call it outside the function it’ll raise an exception. The below diagram explain the types of namespaces in Python.

What is the scope in Python

This means that in our welcome_msg function the welcome_text variable can’t be called outside the function. Let’s see an example.

language = "python"

def welcome_msg(name):
    welcome_text = "Dear {name} welcome to our guide to {language} functions"
    welcome_text.format(name=name, language=language)
    return welcome_text

The language variable can be called inside the function.

To continue with the other functions examples. In previous functions, we didn’t add logic. It was returning a text. In the check_type function, we added conditions to check the type of the number.

The function should have a single goal this requires to validate the function inputs. It’s a necessary part of any function to avoid unwanted behavior. Without the checking type of input, the user can pass a string or a dictionary. The code will try to divide it by 2 it’ll raise an exception. Adding instance type validation will help make this function usable.

The return statement in Python functions can return any type of data. This is what we added in the dictify function. The  Function returns a Python dictionary. This makes it easy to assign the return result of the function to a variable and work with it. Now Let’s call the functions we created and see it’s output.

How to call a function in python

To call a function in python simply mention the function. This will invoke the function logic and return the result. let’s call the above functions.

# print the falue of sum_static
print(sum_static())

# output:
3


x = 2
y = 2

# Passing arguments to the function 
result = sum_dynamic(x, y)
print(result)

# output:
4

# print the welcome message by passing name directly
result = welcome_msg("John")
print(result)

# output:
Dear John welcome to our guide to Python functions


# Apply the function logic multiple time inside a for loop 
numbers = [5, 8, 9, 87, 12, 67]
for number in numbers:
    result = check_type(number)
    print(result)

# output:
Odd
Even
Odd
Odd
Even
Odd


key = "name"
value = "John"

# assign a function to a variable and use it.
data = dictify(key, value)
print(data)
print(data[key])

# output:
{'name': 'John'}
'John'

We called the functions we created and used them in different cases.

conclusion

Python functions are extremely helpful in different Python applications. You can use it to avoid writing the same logic multiple times. A general rule if you’re writing the same code twice add it to a function and call it. To define a function in python we use def. Each function has it’s scope. This will make the variables defined inside the function not accessible outside it. To call the function you just need to write its name with proper arguments if needed. You can assign the return result to a variable and use it. check what we did in the dictify function.