Python Functions Guide
Python Functions Guide
Aug 05, 2022
Python Programming

In this guide, you will learn all you need to know about Python functions, and especially how to properly write and call functions in Python.

By the end of this guide, you will have learned about:

  • What functions are in programming
  • Functions in Python language (The differences between Functions, Methods, Parameters, and Arguments)
  • How to define a Function in Python
  • How to call Functions in Python

And more.

Without further ado, let us begin this guide with the basics: what actually are functions?

What are Programming Functions?

In the programming context, a function is a self-contained module of codes that can be used over and over again to accomplish a specific task. 

Most functions take in data as their input, process it, and then return a result as their output. Once a function is created, it can be used over and over again by calling the function's name. Basically, the programmer can forget all the details of how the function was written.

Using functions allows programmers to focus on the bigger objective while breaking down a problem into smaller components, and they don't have to write the same code multiple times.

In modern programming, functions are almost always used, and most major programming languages include built-in functions. 

There are three basic considerations when dealing with functions in programming: 

  • Define: writing or creating a function from scratch. The programmer can call other functions within this newly-defined function when needed
  • Call: the process of calling a defined function (or a built-in function within the programming language) so the function will execute itself
  • Parameters: when calling functions, the programmer must give the inputs (or parameters) to the function. Parameters must be given each time the function is called

Functions in Python Language

There are three types of functions in Python:

  1. Built-in functions

Python also has its own built-in functions.

Format(value[, format_spec]) is an example of Python's built-in functions used to convert a value to a specific format as controlled by format_spec.

Help([object]) is another built-in Python function to access Python's built-in help system.

  1. Anonymous functions

In Python, anonymous functions are functions that are defined without the def keyword, and hence, without a name.

Anonymous functions are instead defined using the lambda keyword, and so they are also often called lambda functions.

  1. User-Defined functions

Or UDFs, are functions created and defined by users (programmers) to help them in their program. User-Defined Functions will be the main focus of this guide.

Python: Methods vs. Functions

Python is an object-oriented programming language, and in Python, a method is a type of function that you can call on an object. Think of a method as a function to execute on this specific object.

Methods in Python have many similarities to functions, except for two main differences:

  • The method is only used for the object for which the method is called
  • The method is accessible to data that is contained only within the class

Therefore, to really understand Python methods and their differences with functions, we have to first learn about classes and objects in Python.

Classes and objects in Python

Being an object-oriented language, almost everything in Python is an object. 

An object in Python or any programming language is technically a collection of data (called variables) and methods (which are functions) that are executed on that data.

A class, on the other hand, is an object constructor, and we can think of it as a sketch or a blueprint for a specific object.

Let's assume we are going to build a house as an object. We have a design blueprint containing all the details about the house's layout, floors, doors, window placements, etc. Based on this blueprint, we can build the house. 

In this example, the house's blueprint is a class, and the house itself is an object.

Methods as functions within a class

Now that we've understood the roles of objects and classes in Python, we can properly understand methods. 

To reiterate, a method in Python refers to a function when it is part of a class. Meaning, all Python methods are functions, but not all functions are methods. 

In Python, methods can only be accessed with an object or instance of the class, while there's no such restriction with standalone functions.

Python also has a set of built-in methods that you can use off the bat.

Parameters and Arguments in Python Functions

In relation to Python functions, parameters are variables acting as placeholders for the actual values needed by the function. Typically parameters are listed inside the parentheses in a function's definition.

The term "argument" is often used interchangeably with "parameter," and basically, they refer to the same thing: placeholder of information that is passed into the function or method.

However, from the function's technical perspective, an argument is the value of the parameter (as a placeholder) that is passed into the function. The function (or the method) refers to the arguments by their parameter names, while arguments' values are defined by users.

For example, if there are two parameters defined: cost and restaurant-name, then $10 (for cost) and "El Bulli" are arguments that correspond to the parameters cost and restaurant-name.

Simply put, when defining a function, we also define the parameters. Then, when this function is called, you need to specify the value for the arguments for each parameter.

For example: 

def subtractNum(num1, num2):

    print(num1 - num2)

subtractNum(8, 4)

# Output: 4

In the above example:

  • Two arguments are passed into a function named subtractNum
  • The program is ordered to print the subtraction of the two arguments to the terminal
  • The function is called after specifying the values for the 2 arguments (in the above example, num1 is 8 and num2 is 4)

How to Define Functions in Python

As discussed, writing and calling User-Defined Functions (UDFs) will be the main focus of this guide, and there are basically four key steps to defining UDFs in Python:

  1. Use def to declare (define) the function, and then follow def with the function name of your choice.
  2. Add parameters to the function. The parameters should be included within the parentheses following the function, followed by a colon to end the line.
  3. Add statements that the function should execute
  4. End the function with a return statement if the function should produce an output. Without the return statement, the function will always return the object "None."

For example, if you are going to define a function called Test with parameters number1 and number2 to display the sum of the two variables on screen, by following the four steps above, we can write:

def test(number1, number2):

return (number 1+number2) 

Of course, in practice, the function would be much more complex and will get more complex as you continue writing the program.

The return keyword in Python functions

In the above function example, you can use the built-in function print, and in this case, you don't really need to return the function since there won't be any difference between using return or not using it.

def test(number1, number2):

print ("number 1+number2"

There won't be any difference in output between the function above (using return) and this function (with print.)

However, that's not saying the return keyword doesn't have its unique utility. If you want to continue the program using the result of your initial function and execute operations on this result, you'll need the return statement so the function will actually return a usable value (i.e., calculable integers.)

Another important thing regarding the return keyword is that you can use the return keyword to return multiple values by using tuples. 

Tuples in Python are quite similar to standard lists, but you will not be able to modify the elements of a tuple once it's already assigned, unlike in standard lists where you can modify the elements.

More about parameters and arguments when defining functions

As discussed, you can pass argument(s) into a Python function by writing the parameters inside the parentheses following the defined function name.

The basic syntax for defining a function complete with parameters is as follows:

def functionName(par1, par2, par3)

Keep in mind that you can specify as many parameters and arguments as you'd like.

Different types of arguments

There are four different types of arguments that Python functions can take:

  1. Default arguments
  2. Keyword arguments
  3. Required arguments
  4. Variable number of arguments
  1. Default arguments

As the name suggests, default arguments will take a default value if no argument value is passed. You can assign this default value for each parameter when defining the function with the assignment operator (=,) for example:

def test(x,y = 2):

  return x + y

# If no x argument value given, call `test()` with `x` parameter

 test (x=1)

# If no a and b argument values given, call `test()` with `x` and `y' parameters

test(x=1, y=2)

  1. Keyword arguments

This type of argument is identified by its parameter name, and you can use a keyword argument to make sure all parameters are called in a specific order.

Using the same example as the above:

def test(x,y = 2):

  return x + y

# call `test()` with parameters

 test (2,3)

# Call `test()` with keyword arguments

test(x=1, y=2)

  1. Required arguments

Again, as the name suggests, the required arguments must be given value by their users during the function call, or else the function won't be executed properly.

Using the same example as the above:

def test(x,y = 2):

  return x + y

  1. Variable number of arguments

you can use args inside the parentheses in case you don't know the exact argument value (or values) that you want to pass to the function:

# Define `test()` function to accept a variable number of arguments

def test(*args):

  return sum(args)

# Calculate the sum

test(1,3,7)

Anonymous Functions in Python

As discussed, in Python, anonymous functions are also called lambda functions because they are defined using the lambda keyword rather than the usual def statement.

A lambda function in Python can be used wherever function objects are needed with the following syntax:

lambda arguments: expression

As you can see, anonymous functions only have one expression, but can have a number of arguments/parameters.

Here is a simple example of an anonymous Python function that adds 10 to an input value.

# Example of anonymous/lambda functions

test = lambda x: x + 10

print(test(7))

Output=17

In the above example, lambda x: x+10 is an anonymous function. X is the parameter/argument here, and x+10 is the expression that gets returned. As you can see, this function has no name (anonymous) but is assigned to the identifier test. We can call it just as we would a normal function by calling "test."

Thus, the statement:

test = lambda x: x + 10

is similar to this traditional function:

def test (x)

return x + 10

When to use the anonymous/lambda function in Python

We can use anonymous or lambda functions when we need a temporary function for just a short period of time, so we can use a nameless function. 

In Python, we typically use anonymous functions as an argument to another function (a higher-order function that takes in other functions as arguments.) While built-in functions like print(), filter(), and others are more often used by the high-order functions, sometimes lambda functions are also used.

How to Call a Function

Once a function has been successfully defined, you can easily call the function by simply executing the function's name.

For example, to call a function named test(var1, var2), you can simply execute test(1,2), with 1 and 2 being your arguments for parameters var1 and var2.

Want to Learn More?

Congrats! You've reached the end of this short guide on Python functions.

By following the tutorial above, now you already have a solid foundation regarding how to write and call functions in Python and how to effectively use functions in your Python programs.

If you need to learn more, 24HourAnswers.com has experienced Python tutors and more tutorials on Python and other programming languages, where you can learn and practice your knowledge more thoroughly.





View Available Computer Science Tutors