Python Functions

Introduction

Functions are an essential aspect of programming that allow you to encapsulate a set of instructions and logic into a reusable block of code. They enhance code organization, readability, and maintainability. A Python function is a named sequence of statements that performs a specific task. It takes input data, processes it, and optionally returns a result.

Why Use Functions?

Using functions offers several advantages:

  • Modularity: Functions help break down a complex program into smaller, more manageable components, enhancing code organization.
  • Reusability: Once defined, functions can be reused across different parts of your codebase, reducing redundancy and saving development time.
  • Readability: Well-named functions with clear purposes make your code easier to read and understand.
  • Testing: Functions can be tested independently, simplifying the process of identifying and fixing bugs.
  • Collaboration: Dividing work among team members becomes easier when you use functions, as each member can work on specific functions.

Defining/Creating Functions

To define a function in Python, you use the def keyword followed by the function name, a pair of parentheses (), and a colon :. The function body is indented below the def statement.

def say_hello():
    print(f"Hello!")

The example above, defines a function named say_hello that prints a greeting.

Calling Functions

After defining a function, you can call it (i.e. use or invoke it) by writing its name followed by parentheses.

say_hello()

Output:

Hello!

Parameters

A function can also have parameters, which are pieces of data given to the function as a way of modifying how it works.

When a function is defined, the parameters are specified inside the parentheses.

def greet(name):
    print(f"Hello, {name}!")

To call a function has parameters, place the parameter values inside the parentheses of the function call.

greet("Alice")

Output:

Hello, Alice!

Parameters vs. Arguments

A value that is passed to a function when it’s called (as in “Alice” above) is referred to as an argument.

In the context of functions, parameters are the names used in the function definition to represent the inputs the function expects.

Arguments are the actual values passed to the function when it’s called.

In the previous example, name is the parameter when the function is defined, and “Alice” is the argument given to the function when it’s called.

Often the terms “parameter” and “argument” are confused, so here is the bottom line:

When a function is defined it’s parameters, when a function is called, it’s arguments.

Functions With Multiple Parameters

Functions can have multiple parameters. Those are separated by commas when the function is defined.

Arguments are also separated by commas when a function is called.

Example:

def greet_with_full_name(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")
    
greet_with_full_name("Alice", "Chalmers")

Output:

Hello, Alice Chalmers!

Positional Arguments

In the function call as above, the argument values are matched with the function parameters according to the position in which they appear in the function call and definition, respectively.

"Alice" is assigned to first_name because both appear first, and likewise "Chalmers" is assigned to last_name because they appear second.

These types of argument are called a positional arguments.

There are also arguments called keyword arguments, which do not go by position, and will be discussed in a specific lesson about those.

Calling a Function With the Wrong Number of Arguments

If you call a function with the wrong number of arguments, expect an error.

If you call a function with the wrong number of arguments, expect an error.

Example:

greet_with_full_name("Alice")

Output:

TypeError: greet_with_full_name() missing 1 required positional argument: 'last_name'

The function call in the example above only passes one argument, but greet_with_full_name was defined with two, so the result is an error.

Returning a Value From Functions

Functions can also return values using the return keyword followed by the value to return. The return statement causes the function to exit, meaning no other code in the function will be executed, and pass the given value to the statement that called it. The returned value can be assigned to a variable or used directly in expressions involving the function call.

Example:

def add(a, b):
    return a + b

result = add(3, 5)
print(result) 

Output:

8

In this example, the add function returns the sum of its two arguments, which is then assigned to the variable result.

Functions That Return Nothing

Functions that don’t use a return statement, implicitly return the None value. A None is a Python object of type NoneType used to indicate “nothing”.

Example:

def no_return()
    print("I'm printing, but not returning.")
    
 x = no_return()
 print(x)
 print(type(x))

Output:

None
<class 'NoneType'>

In this example the `no_return()` function has no `return` statement. When the variable `x` is assigned to whatever the function returns, we discover that x is a None value, which is an object of type NoneType.

Summary & Reference for Python Function Basics

Functions allow you to encapsulate a set of instructions into reusable blocks of code. They provide modularity, reusability, readability, and ease of testing, making your code more organized and maintainable.


To define a function in Python, use the def keyword followed by the function name, parentheses (), and a colon :. The function’s logic is indented below the def statement

def say_hello():
    print(f"Hello!")

Calling a function involves using its name followed by parenthese.

say_hello()  # "Hello!"

Functions can have parameters, which are the inputs the function expects when it’s called. They are specified inside the parentheses of a function definition.

def greet(name):
    print(f"Hello, {name}!")

Call a function that has parameters by providing their values in the function call.

greet("Alice")  # "Hello, Alice!"

Parameters are names used in function definitions, while arguments are the values passed to the function when called.


Functions can have multiple parameters that are separated by commas when defined. Similarly, arguments are separated by commas when the function is called.

def greet_with_full_name(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")

greet_with_full_name("Alice", "Chalmers")  # "Hello, Alice Chalmers!"

Calling a function with the wrong number of arguments will generate a TypeError.


The return statement exits the function and sends back a value that can be assigned to variables or used directly.

def add(a, b):
    return a + b

result = add(3, 5)  # result --> 8

Functions that don’t use a return statement, implicitly return a None value, which is an object of type NoneType.