Reading Time: 7 minutes
python functions

What is a Python Function? 

In this tutorial, we discuss one of the most useful attributes of Python: the function. Python functions are considered “First Class” objects. A First Class object can be assigned to variables, stored in data structures, passed as arguments to other functions, or even return values from other functions. Other examples of First Class objects in Python are integers, strings, and dictionaries.

A Python function is defined as a reusable section of code created to run a defined action. It runs only when requested from another function or when run from a Python prompt. Functions allow a user to pass data parameters into a code section, which then returns a data result.

There are three basic types of Python functions:

  • Built-In Functions - These functions are a standard part of the Python language. The latest native Python interpreter has 69 built-in functions.
  • Positional Argument Functions - These functions are user-generated with the def keyword.
  • Anonymous Functions - This function is not defined by a specific name. An anonymous function is defined using the lambda keyword, and is also why anonymous functions are also called lambda functions.

We will review these function types next.

Note:
We are using the latest version of python 3.10.0a4 in this article. Using an older version of Python, some of the code snippets may throw an error. Please refer to the Python documentation for your specific version.

Methods

It should be noted that a method is similar to a function in that they both use a set of instructions to perform a task. The difference between them is that a method is associated with an object, while a function is not.

Note:
In every Python script below, #!/usr/bin/python3 is used as the first line called a shebang line. The shebang line describes where the Python interpreter is found. In the following scripts, we have noted that the python3 interpreter (or command) is located in /usr/bin/python3.

Built-In Functions

In comparison to user-defined functions or lambda functions, built-in functions exist without a unique definition and are called directly. We selected one of the most used predefined functions called print() earlier to display an object. Here is a complete list of the built-in functions in python.

To utilize these built-in functions, we merely have to call them and then pass the relevant argument as needed. In this case, we will use the print() function. Here we create a small script called function1.py

#!/usr/bin/python3

print("Python is fun.")
print(1,2,3,4)
print("I declare a thumb war!")

Our output is below.

root@host:~# python3 function1.py
Python is fun.
1 2 3 4
I declare a thumb war!
root@host:~#

User-Based Function

When creating a user-based function, we use the function name followed by a set of parentheses. The parameters are always denoted and should occur after the particular function name. Next, we create a simple python script called function2.py to demonstrate.

#!/usr/bin/env python3
 def user_function():
  print("Hi there! I'm a function!")

user_function()

Below is our output.

root@host:~# python3 function2.py
Hi there! I'm a function!
root@host:~#

Notice the def keyword in front of user_function(). Python uses the def keyword to define the function. The instruction in the section block of the function must be indented. This indented statement forms the body of the function. When running the above command, we get the following output.

#!/usr/bin/env python3
 def user_function(firstname):
  print(firstname + " at Liquid Web")

user_function("David")
user_function("Todd")
user_function("Jackie")

Our output is below.

root@host:~# python3 function3.py
David at Liquid Web
Todd at Liquid Web
Jackie at Liquid Web
root@host:~#

Notice the extra space on line 3 in the " at Liquid Web" string. This blank gap adds a space in front of the word “at,” which ensures the output looks like a complete sentence, as seen in the printed line. 

Anonymous Functions

An anonymous function has no defined name and is dissimilar to the def keyword. In this case, anonymous functions are defined using the lambda keyword.

  • Lambda functions contain a local namespace of their own. They can't access other variables than the ones in their parameter list or the global namespace.
  • The anonymous function requires an expression to call.
  • Lambda forms can take multiple arguments but will return only one expression value. It cannot contain multiple expressions or commands.

What is an Argument?

Information is introduced into a function via arguments. It should be noted that in the Python docs, arguments are often shortened to the smaller term args. A related term is called Keyword Arguments. This term is shortened to kwargs in the Python documentation. Multiple arguments can be added to a function as long as they are separated with a comma.

Arguments or Parameters?

Typically, functions can use the term parameter and argument interchangeably. From the perspective of the function:

  • A parameter is a variable listed within the parentheses inside the defined function.
  • An argument is a value that is sent to a function when called.

Calling a Function

When we define the function, we assign a name to it. To call the function, we use the function name followed by a set of parentheses. This identifies the parameters that will be included within the function itself and improve the code block structures.  In the example below, we demonstrate this concept. 

#!/usr/bin/python3
 # Here we define the Function
 def printme(user_string):
        "The function defined as printme, prints this string."
        print (user_string)
        return;
 # Now, we can call the printme function at anytime later in the code
 printme("this is the first call to the user defined function above.")
 printme("This is the second call to the same function defined above.")

When running the above command, we get the following output.

root@host:~# python3 function4.py
This is the first call to the user defined function above.
This is the second call to the same function defined above.
root@host:~#

Once the function’s basic structure is complete, we can run it by calling it from another function or directly from the Python prompt.

It should be noted that variables defined within a function are locally scoped. This means that a variable defined inside a function is only recognized within that function. Variables within a function only persist while the function is being executed. Global variables are defined outside the function using the global keyword and persist even after being executed by the function.

Passing Arguments to a Function

Use one of the four following arguments to call functions.

  • Default Arguments - This argument assumes that a default value is used if one is not provided for the function call.
  • Keyword Arguments - When a keyword argument is used in a function call, the keyword argument call identifies the parameter name's arguments. This lets us place the arguments out of order or skip them. We can do this because the Python interpreter can use the provided keywords to match the parameters' values.
  • Required Arguments - These are the arguments that are passed to a function within a precise positional order. This means that the number of arguments required in the function should match the number of arguments needed to define the function.
  • Variable-Length Arguments - If we need to process more arguments than is called for in the function definition, variable-length arguments are used. Unlike the required and default argument types, these arguments are unnamed in the function definition.

Recursion

The definition of recursion is a process that defines something in terms of itself. This means that a recursion function calls back to itself until the problem is solved. This function runs a set of instructions repeatedly, calling back to itself until it has completed its run. This means that we can loop the output data back through the function until the desired result is reached. In the image below, we see how the function works.

# here we assume that remainder is a positive integer
 def hi_recursive(remaining):
     # here is the base case - when the remainder = 0
     if remaining == 0:
         return
     print('hi')
     # Call to the function itself, with a reduced remaining count
     hi_recursive(remaining - 1)

A recursive function generally has two parts:

  • The base case, which is the identifier that determines when the recursive function will stop.
  • The call to itself.

Below is an example of a recursive function to find the factorial of an integer. A factorial of a number is the product of all the integers from one to that number. Here we use num = 3.

#!/usr/bin/python3
def factorial(x):
    """This is a recursive function to find the factorial of an integer"""
        if x == 1:
           return 1
        else:
           return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Our output shows this.

root@host:~# python3 function6.py
The factorial of 3 is 6
root@host:~#

In the code example above, factorial() is a recursive function as it calls itself. When we call this function using a positive integer, it recursively calls to itself by decreasing the number. Each function multiplies the number with the factorial of the number below it until it is equal to one. The following diagram explains this recursive call.

factorial(3)          # 1st call with 3
3 * factorial(2)      # 2nd call with 2
3 * 2 * factorial(1)  # 3rd call with 1
3 * 2 * 1             # return from 3rd call as number=1
3 * 2                 # return from 2nd call
6                     # return from 1st call

The recursion function ends when the number reduces to one. This is the base condition.

One should be careful in using this type of function. If set up improperly, a function may fail to terminate or use an excessive amount of memory or processor power. However, when correctly implemented, recursion is an efficient and elegant approach to address an issue.

Conclusion

This completes our tutorial on Python functions. A Python function is a group of related statements designed to perform a specific task. The thought behind this is to use the same code repeatedly, using different inputs to produce an alternate output. These functions can be defined to achieve multiple goals within a Python program. Overall, this is one of the major building blocks of the Python programming language. 

We pride ourselves on being The Most Helpful Humans In Hosting™!

Our Support Teams are filled with experienced Linux technicians and talented system administrators who have intimate knowledge of multiple web hosting technologies, including those discussed in this article. Should you have any questions regarding this information, we are always available to answer any inquiries with issues related to this article, 24 hours a day, 7 days a week 365 days a year.

If you are a Fully Managed VPS server, Cloud Dedicated, VMWare Private Cloud, Private Parent server, Managed Cloud Servers, or a Dedicated server owner and you are uncomfortable with performing any of the steps outlined, we can be reached via phone at 800.580.4985, a chat or support ticket to assist you with further information.

About the Author: David Singer

I am a g33k, Linux blogger, developer, student, and former Tech Writer for Liquidweb.com. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Have Some Questions?

Our Sales and Support teams are available 24 hours by phone or e-mail to assist.

1.800.580.4985
1.517.322.0434

Latest Articles

What is an Intrusion Prevention System (IPS)?

Read Article

Premium Business Email Pricing FAQ

Read Article

What is the Fortran Programming Language?

Read Article

Microsoft Exchange Server Security Update

Read Article

How to Monitor Your Server in WHM

Read Article