Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. functions
13 min read

Functions

A function is a block of code that only runs when it is called. It performs a specific task, often one that needs to be completed more than once. Functions are abstracted to take parameters, which are values input to the function and used inside.

Python provides a series of built-in functions, such as print(), dict(), len(), etc, but you can also create your own functions. These are known as user-defined functions.

Defining a Function

Functions are defined using Python's def keyword. Functions are labeled by their name and the arguments they take. Functions are called using parentheses (), inside which are the parameters to that function.

Warning
Unlike C++ or Java, Python has no function overloading. Defining a second function with the same name replaces the first, whatever its parameters. To accept different combinations of arguments, use default and variable-length arguments instead.

Here is a simple example of function syntax. This is a valid function.

python
1from datetime import datetime    # gives us the current time
2
3def my_print(string):
4    """Method prints the string with time"""
5

Let's carefully consider each part of the function syntax:

  • Signature: The signature is the line containing the function's name and parameters. This line must end with a colon (:) indicating the start of the function body.
  • Function body: Each line of the function body is indented one level.
  • Function Docstring: The function docstring is directly below the signature line. It indicates what the function does and may contain key information on the parameter types and expected return.
Warning
Remember that indentation must be consistent across the entire file. Four spaces is the standard (PEP 8); mixing tabs and spaces raises a TabError.

Note that this function does not have a return statement. Return statements are optional in Python and are only needed when something needs to be returned. Functions that don't have return statements automatically return None. Here is an example of a function with a return:

python
1def my_sum(arg1, arg2):
2    # demonstrating early return
3    if arg1 == 10 or arg2 ==

Notice that Python will allow you to return two different types from the same function. This is part of dynamic typing.

Calling a Function

Once your function is complete, you can execute it by calling it from another function or directly from the Python REPL. Here, we call our my_print function from before:

python
my_print("Running test cases...")    # Console: 22:03:10: Running test cases...

Pass by Reference vs. Pass by Value

Python passes every argument as a reference to an object: the parameter inside the function (the callee) and the variable in the calling function (the caller) are two names for the same object. If the callee changes that object in place, the caller sees the change. For example:

python
1def change_list(lst):
2    lst[0] = 1
3    lst[1] = 

Running this yields the following output:

python
1List before change: [10, 20, 30]
2List inside function: [1, 2, 3]
3

Here is an example of how someone might mistakenly not change the values outside the function. Instead of changing the list, it assigns a new one.

python
1def change_list(lst):
2    lst = [1, 2, 3]
3    print(

Running this yields the following output:

python
1List before change: [10, 20, 30]
2List inside function: [1, 2, 3]
3
Why does this happen?
In the first example, lst[0] = 1 changes the list object itself, which my_lst also refers to. In the second example, lst = [1, 2, 3] creates a brand-new list and points the local name lst at it. my_lst still refers to the original list, which nothing changed.

In short, the caller sees changes made to the object, but not reassignments of the parameter name. This is also why a function can never change a caller's int or str: those types are immutable, so the only way to "change" one is to reassign the name.

You can read more about how Python handles scope in the Variable Scope section.

Let's expand on the above explanation and show what happens when you send an immutable object into a function expecting a mutable object.

python
1>>> change_list("string")
2Traceback (most recent call last):
3  File "<stdin>", line 1, in <module

If you have a mutable type and want to ensure that you don't modify it inside the callee function, use the type's copy() method to make a copy. Lists also support a full slice (lst_copy = lst[:]) to make a full copy.

Function Arguments

Functions can be called using one of the four types of formal arguments:

  1. Required arguments
  2. Keyword arguments
  3. Default arguments
  4. Variable-Length arguments

Required Arguments

Required arguments are your "standard" arguments. These must be passed to the function in the correct order, matching the function's signature.

If you incorrectly place the number of parameters, Python will raise a TypeError:

python
1from datetime import datetime
2
3def my_print(string):
4    """Method prints the string with time"""
5

Keyword Arguments

Keyword arguments allow you to enter arguments out of order by referencing their name when calling the function. The one downside to this method is not knowing the argument's name in the signature, especially if the function is from an external library.

python
1def print_user(uid, name, age):
2    print("===USER===")
3    print("ID:", uid

This successfully prints as expected:

===USER===
ID: 65535
Name: John
Age: 30

Default Arguments

A default argument assumes a default value if none is provided. The function's signature labels this with an equal sign after the variable name and its default value. Here is an example:

python
1def print_user(uid, name, age=21):
2    print("===USER===")
3    print(

This yields the following output:

===USER===
ID: 65535
Name: John
Age: 30
===USER===
ID: 65535
Name: John
Age: 21
Warning
Default arguments must come last. Otherwise, it raises a SyntaxError:
python
1def func(a=10, b):
2               ^
3

Variable-Length Arguments

Sometimes, you may need to write a function that takes an unknown number of arguments. These are variable-length arguments, collected under a single name in the function definition.

The first type of variable-length argument list is a non-keyword variable argument (*args). An asterisk (*) is placed before the variable name to denote this, and the extra positional arguments arrive as a tuple. The tuple remains empty if no additional arguments are specified. Here is an example:

python
1def print_user(name, *args):
2    print("===" + name + "===")
3    for

Now, we can use this to support any number of arguments.

python
1>>> print_user("John")
2===John===
3>>> print_user("John", "65535", 
Info
Note that we are still required to provide an argument for name, meaning print_user() would raise a TypeError.

The other type of variable-length argument is a keyword variable-length argument (**kwargs). Two asterisks are placed in front of the variable name, and the extra keyword arguments arrive as a dictionary of names to values.

python
1def print_user(name, **kwargs):
2    print("===" + name + "===")
3    

This lets us be more specific in the values being printed for the user.

python
1>>> print_user("John")
2===John===
3>>> print_user("John", uid="65535",
Danger
Be careful putting a parameter after *args. Python allows it, but that parameter becomes keyword-only: the only way to pass it is by name. (**kwargs must always come last; anything after it is a SyntaxError.)
python
1def print_user(name, *args, delimiter):
2    print

Variable Scope

Not every variable can be used from everywhere in a program.

The scope of a variable determines the portion of the program that has access to it. In Python, there are two basic scopes: global variables and local variables.

Global vs. Local

Variables defined inside a function body have a local scope, and those defined outside a function have a global scope.

Therefore, local variables can only be accessed inside the function they're declared in, whereas global variables can be read throughout the program body. Assigning to a name inside a function makes it local to that function, even if a global with the same name exists:

python
1# global scope
2total = 0
3
4def my_sum(arg1, arg2):
5

This returns:

Local total: 30
Global total: 0

Using global

The global keyword tells Python that a name inside a function refers to the global variable, so assigning to it changes the global.

python
1# global scope
2total = 0
3
4def my_sum(arg1, arg2):
5

This returns:

Local total: 30
Global total: 30
Info
If the global keyword is used and that variable is not already defined globally, the assignment inside the function creates it. Therefore, removing the total = 0 line in the last set of code yields the same result.
Tip
Reach for global sparingly. A function that returns its result is easier to test and reason about than one that changes a variable somewhere else.

Function Type Hints

Type hints indicate the expected parameters and the return type of a function. Python itself ignores them at runtime, so passing the wrong type still runs, but they document what a function expects and let tools check your code before you run it.

To add type hints, use colons after parameter names and then a return arrow (->) before the return type. Here's an example that helps warn the user not to put a string into our list function:

python
1def change_list(lst: list[int]) -> None:
2    lst[0] = 1

Here is a list of benefits of Type Hints:

  1. Readability: This ensures functions are more readable and helps other developers understand the input and output of the function.
  2. IDE Support: Using type hints allows IDEs to recognize the function's parameters and return and provide autocomplete support for that function.
  3. Documentation: Type hints are documentation and an easier way of showing how the function works than using the Docstring.
  4. Debugging: A type checker such as mypy or Pyright reads your hints and reports type-related errors before the code ever runs.

The most common Type Hints are:

TypeDescriptionExample
intIntegerint
floatFloating-point numberfloat
strStringstr
boolBooleanbool
list[type]List of elements of type typelist[int]
tuple[type, type]n-Tuple with specified typestuple[int, int, str]
dict[key, value]Dictionary with key-value typesdict[str, int]
type | NoneThe type, or Nonestr | None
now
=
datetime
.
now
(
)
6 print(now.strftime("%H:%M:%S") + ": " + string)
10
:
4 return "You can't do this!"
5
6 # now add the two items
7 return arg1 + arg2
8
9total = my_sum(5, 8)
10print("First total:", total) # Console: First total: 13
11
12total = my_sum(5, 10)
13print("Second total:", total) # Console: Second total: You can't do this!
2
4 lst[2] = 3
5 print("List inside function:", lst)
6
7# calling change_list
8my_lst = [10, 20, 30]
9print("List before change:", my_lst)
10change_list(my_lst)
11print("List after change:", my_lst)
List after change
:
[
1
,
2
,
3
]
"List inside function:"
,
lst
)
4
5# calling change_list
6my_lst = [10, 20, 30]
7print("List before change:", my_lst)
8change_list(my_lst)
9print("List after change:", my_lst)
List after change
:
[
10
,
20
,
30
]
>
4 File "<stdin>", line 2, in change_list
5TypeError: 'str' object does not support item assignment
now
=
datetime
.
now
(
)
6 print(now.strftime("%H:%M:%S") + ": " + string)
7
8my_print() # TypeError: my_print() missing 1 required positional argument: 'string'
9my_print("string1", "string2") # TypeError: my_print() takes 1 positional argument but 2 were given
)
4 print("Name:", name)
5 print("Age:", age)
6
7print_user(name="John", uid="65535", age=30)
"ID:"
,
uid
)
4 print("Name:", name)
5 print("Age:", age)
6
7print_user("65535", "John", 30)
8print_user("65535", "John")
SyntaxError
:
parameter without a default follows parameter
with
a default
arg
in
args
:
4 print(arg)
30
)
4===John===
565535
630
for
key
,
value
in
kwargs
.
items
(
)
:
4 print(key + ": ", value)
age
=
30
)
4===John===
5uid: 65535
6age: 30
(
"==="
+
name
+
"==="
)
3 for arg in args:
4 print(arg)
5 print(delimiter)

Running this:

python
1>>> print_user("John", "65535", 30)
2TypeError: print_user() missing 1 required keyword-only argument: 'delimiter'
3>>> print_user("John", "65535", 30, delimiter="=========")
4===John===
565535
630
7=========
# local scope
6 total = arg1 + arg2
7 print("Local total:", total)
8 return total
9
10my_sum(10, 20)
11print("Global total:", total)
global
total
# convert to global scope
6 total = arg1 + arg2
7 print("Local total:", total)
8 return total
9
10my_sum(10, 20)
11print("Global total:", total)
3 lst[1] = 2
4 lst[2] = 3
5 print("List inside function:", lst)