Python Functions

A tutorial on Python Functions and how to use them.


A function is a reusable block of code that runs only when called. Functions save time, increase code re-usability and makes your code simpler and easier to read.

Functions make use of arguments and parameters to receive data and output a result accordingly. This allows for a greater deal of flexibility on your code, since this allows your functions to receive all kinds of different data, and output different results.

Defining a Function

  • Python Functions are defined using the def statement, followed by a unique name.
  • Any statements you wish to execute are written in the code block beneath it.
  • A function can have input parameters or arguments placed within it’s parentheses.
  • A semi colon is added after the function name.

We’re leaving the function parameters blank for now.

def testfunction():
    print("Hello World")

Calling a Function

A function is not run until it is triggered by a function call. A function call is simply the name of the function and appropriate arguments included in the parentheses.

def testfunction():
    print("Hello World")


As they are no function parameters present, we’re not including any arguments in our function call.

Arguments and Parameters – The difference

These two terms are very interchangeable with each other, so knowing the difference isn’t that big a of deal. The terms they refer to are almost identical. To sound more professional though, correct terminology is important.

Parameters are the variables present in the parenthesis during function definition.
When a method is called, the arguments are the data you pass into the method’s parameters.

Function arguments

Arguments are used to pass information into the function from the rest of the program. The function can then be used to process this data and return a result.

There is no limit to the number of Arguments that can be written. There may even be no arguments at all, depending on the kind of function you’re making. Use commas to separate arguments in a function.

Keep in mind the number of arguments you insert into a function call. The number of arguments should be exactly equal to the number of parameters.

Function Example

In the example below, the variable name is the input parameter, where as the value, “Jim”, passed in the function call is the argument.

def testfunction(name):
    print("Hello " + name)


The rest is self -explanatory. The function takes “Jim” as an input, concatenates it to “Hello” and prints it. This function can be run as many times as you wish simply by repeating the function call.

Functions with Multiple Arguments

Note the multiple parameters, the arguments and the two function calls in the below Python code.

def add(num1,num2):
    result = num1 + num2

# Output

Returning a Function

If you wish to return some values from the function to the rest of the program, you can use the return statement. As the name suggests, it returns a value without printing it. Executing this statement will cause the Python function to end immediately and store the value being returned into a variable.

In the example below, instead of being displayed on screen, the value of result was returned into the variable a. This allows us to use the result value later in the program.

def add(num1,num2):
    result = num1 + num2
    return result

a = add(2,3)

You can also use the return statement as a way to quickly stop the function. You don’t have to add anything after the return statement if stopping the function is only intention.

def example(x):
      if x < 0:
          print("X is greater than 0")

Variable Scope – Python Functions

While dealing with Python Functions you have to keep variable scope in mind as well.

The code inside a function is in it’s own little world, separated from the rest of the program. Any variable declared in the Function is not considered by the rest of the program. This allows for two variables of the same name to exist, one inside the function, and the other outside it. This isn’t good practice however. All variables names should be unique, regardless of it’s scope.

Local Variable: A variable defined within a function, and can only be used within that specific function. With reference to the local variable, the area in a function is referred to as the “local scope”.

Global Variable: A variable defined in the main programming body. And unlike local variables, they can be accessed from both local and global scopes.

Attempting to access a local variable

Attempting to access a variable defined within a function will produce an error, as the variable result does not exist within the global scope.

def add(num1,num2):
    result = num1 + num2

NameError: name 'result' is not defined

Accessing a global variable from a local scope

It’s not possible to outright access a global variable from a local scope. The function will get confused as to whether you are referring to a local variable, or a global one. Hence, any global variables you wish to use in a function must be explicitly labelled as global.

def nameprinter():
    global names
    for x in names:

names = ["Jim","Sam","Bob"]

If the global keyword is not included, the same error will thrown as shown in the previous example.

Inbuilt functions in Python

Inbuilt functions have nothing to do with everything explained above, however I wish to explain them to build your understanding.

Most people don’t realize it, but statements like int() and str() are actually just functions. Just like the functions we made above. There is nothing special about the name int. It’s just the name to the block of code that will convert a string into an integer. The same goes for all other such functions. Every programming language comes with these built-in-functions which perform basic tasks to aid us in our development.

On an advanced level, you can expect to be making your own custom libraries and built-in-functions for your projects.

Recursion in Python Functions

A recursive Function is a function that calls itself during it’s execution. This causes the function to run several times outputting it’s result at the end of each iteration.

Recursion significantly improve the readability and size of your code if used correctly. It is especially good for working on things that have many possible branches and are too complex for an iterative approach. 

However, a recursive approach is more resource intensive and if not handled correctly, will result in an infinite loop where the function keeps calling itself.

A simple example of a recursive function in Python.

def factorial(n):
    if(n <= 1):
        return 1

See more on recursion here.

This marks the end of our Functions in Python Article. If you have any suggestions or contributions to make, please do so. We welcome anything to help improve our site, CodersLegacy.

Notify of
Inline Feedbacks
View all comments