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.
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.
Here is a simple example of function syntax. This is a valid function.
1from datetime import datetime # gives us the current time
2
3def my_print(string):
4 """Method prints the string with time"""
5Let's carefully consider each part of the function syntax:
:) indicating the start of the function body.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:
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.
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:
my_print("Running test cases...") # Console: 22:03:10: Running test cases...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:
1def change_list(lst):
2 lst[0] = 1
3 lst[1] = Running this yields the following output:
1List before change: [10, 20, 30]
2List inside function: [1, 2, 3]
3Here 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.
1def change_list(lst):
2 lst = [1, 2, 3]
3 print(Running this yields the following output:
1List before change: [10, 20, 30]
2List inside function: [1, 2, 3]
3lst[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.
1>>> change_list("string")
2Traceback (most recent call last):
3 File "<stdin>", line 1, in <moduleIf 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.
Functions can be called using one of the four types of formal 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:
1from datetime import datetime
2
3def my_print(string):
4 """Method prints the string with time"""
5Keyword 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.
1def print_user(uid, name, age):
2 print("===USER===")
3 print("ID:", uidThis successfully prints as expected:
===USER===
ID: 65535
Name: John
Age: 30A 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:
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: 21SyntaxError:1def func(a=10, b):
2 ^
3Sometimes, 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:
1def print_user(name, *args):
2 print("===" + name + "===")
3 forNow, we can use this to support any number of arguments.
1>>> print_user("John")
2===John===
3>>> print_user("John", "65535", 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.
1def print_user(name, **kwargs):
2 print("===" + name + "===")
3 This lets us be more specific in the values being printed for the user.
1>>> print_user("John")
2===John===
3>>> print_user("John", uid="65535",*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.)1def print_user(name, *args, delimiter):
2 printNot 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.
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:
1# global scope
2total = 0
3
4def my_sum(arg1, arg2):
5This returns:
Local total: 30
Global total: 0The global keyword tells Python that a name inside a function refers to the global variable, so assigning to it changes the global.
1# global scope
2total = 0
3
4def my_sum(arg1, arg2):
5This returns:
Local total: 30
Global total: 30global 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.global sparingly. A function that returns its result is easier to test and reason about than one that changes a variable somewhere else.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:
1def change_list(lst: list[int]) -> None:
2 lst[0] = 1
Here is a list of benefits of Type Hints:
The most common Type Hints are:
| Type | Description | Example |
|---|---|---|
int | Integer | int |
float | Floating-point number | float |
str | String | str |
bool | Boolean | bool |
list[type] | List of elements of type type | list[int] |
tuple[type, type] | n-Tuple with specified types | tuple[int, int, str] |
dict[key, value] | Dictionary with key-value types | dict[str, int] |
type | None | The type, or None | str | None |
Running this:
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=========