1. python
  2. /basics
  3. /functions

The Basics of Python Functions

Getting Started

In programming, functions enable us to break down complex problems into smaller, manageable chunks. Moreover, they give us reusable pieces of code that we can call multiple times with different inputs.

In Python, we can use both built-in and user-defined functions to solve our problems. The first ones, are pre-written and available to us as soon as we start using the language. On the other hand, user-defined functions are the ones we create ourselves.

So, let's dive in and take a look at their syntax, and provide an overview of crucial, adjacent concepts.

Python Function Types

There are three types of functions available to us. We'll mostly focus on the functions we define ourselves. However, we'll also mention the built-in ones that Python provides, and save lambda functions(anonymous functions) for another article.

Built-in Python Functions

Python comes with a variety of built-in functions that we can leverage in our code. Going through the basics, we already saw the usage of some common ones such as print(), type(), len(), str(), int(), float(), and input(), just to name a few.

Let's illustrate an example with the print function:

# using the print() function
print("Python Basics on Web Reference")

When we run the code above, we'll see the following output:

Python Basics on Web Reference

You can check out the official documentation on built-in functions to learn more in detail.

The Difference Between Methods and Functions

In Python, a method is a function that is part of a class. We can access methods through an instance or object of those classes. On the other hand, functions are standalone concepts that can be used anywhere in our code, regardless of whether they are part of a class or not.

In other words, all methods are functions, but not all functions are considered methods.

User-Defined Functions

Naturally, we can also create our functions. To create a simple user-defined function, we use the def keyword, followed by its name and a set of parentheses, like so:

# creating a user-defined function
def greet():
    print("Hello Python novices!")

# calling the user-defined function

# Output: Hello Python novices!

The Syntax of Python Functions

Now that we have an understanding of the rudimentary structure, we can also introduce other elements that a function can contain. Below, we'll break down a fully defined function.

# creating a user-defined function
def function_name(parameters):
    # body of the statement
    return expression
    # Function return

# calling the user-defined function
  • function_name : Logically, this refers to how we can name functions. The naming should be descriptive and meaningful, and it should follow the same naming conventions as any other variable in Python (i.e. no spaces, no special characters, and starting with a letter).

Find out more about naming and variables here.

  • parameters: These represent the input values that the function accepts. They are optional, and a function can exist without them as we saw in the first examples, or it can have multiple parameters separated by a comma.

  • body of the statement: The code block inside the function that defines what the function does. It can contain any valid Python code and can use any of the concepts and constructs available, such as loops, conditionals, variables, etc.

  • return expression: With the return keyword we specify the value that the function should return. Additionally, this can be any valid Python expression that produces a value. However, if the function doesn't return any value, we can omit the keyword.

  • function call: To call a function, we use the name of the function followed by a set of parentheses. If the function takes any arguments, we pass them within the parentheses, separated by commas.

As such, we can insert this structure anywhere in the body of a Python script, as long as it's indented correctly.

Now, we'll illustrate that with a custom function that takes a number as an argument and returns the result of a division operation.

def divide_by_2(num):
    result = num / 2
    return result

# Calling the function with an argument
division = divide_by_2(10)

# Printing the value of the division variable

When we run the code above, we'll see the following output:


As you can see, we defined a function called divide_by_2 that takes a single parameter num. The function then divides num by 2 and returns the result. We then call the function with the argument 10, store the result in a variable called division, and finally, print the value of the division.

The Difference Between Parameters and Arguments

You might notice that these terms are usually used interchangeably. However, the main difference is that parameters are defined at the beginning of a function, while arguments are the values that are passed to the function when it's called.

Let's expand our rudimentary example to understand how they differ:

def greet(name):
    return "Thank you " + name

# calling the greet() function with an argument
gratitude = greet("Guido Van Rossum!")

# printing the value of the greeting variable

When we run the code above, we'll see the following output:

Thank you Guido Van Rossum!

We see a function called greet being defined with a single parameter name. The function returns a string that concatenates the string "Thank you " with the value of the name parameter.

Next, we call the function by passing an argument "Guido Van Rossum!" to it and storing the returned value in a variable called gratitude. Finally, we print the value of the variable to the console.

With this, we demonstrate the difference; the name parameter is defined as part of the function definition, while the argument "Guido Van Rossum!" is passed when we call the function. Simply put, the argument provides a specific value for the function to use as the value of the parameter.

Bear in mind that the number of arguments that a function is called with must match the number of parameters that the function is defined with. If the number of arguments doesn't match the number of parameters, an error will occur.

Argument Types

Now that we have a clear understanding of the difference between parameters and arguments, let's dive into the different types of arguments available in Python. Some of these include positional and keyword arguments, as well as default ones.

For now, we'll take a closer look at default arguments and delve into the remaining types in subsequent articles.

Default Arguments

Default arguments are automatically assigned a default value if we don't provide a value when the function is called.

def describe_car(make="Tesla"):
    print("The car is a " + make)

describe_car("Ford") # Output: The car is a Ford
describe_car() # Output: The car is a Tesla

We have a function called describe_car that takes one argument: make. When we call the function with an argument, like describe_car("Ford"), it uses the value we provided. However, if we call the function without any arguments, like describe_car(), it uses the default value of "Tesla" for the parameter make.

Final Thoughts

With this, we covered the basics of declaring and calling functions alongside arguments and the return statement.

Additionally, we compared functions to methods and briefly touched upon default arguments, which provide a default value for a function argument, making our functions more flexible and easy to use.

Now that you've gained a solid understanding of functions in Python, we encourage you to put your newfound knowledge into practice. The more you experiment with them, the more you'll understand their full potential and how they can help you solve complex problems.

Useful Resources

Official Documentation for Built-in Functions in Python

Function and Class Definitions

The Basics of Variables in Python