Defining and Using Functions in Python
Learn about functions in Python, including how they run when called, accept parameters, and return results. Discover the basics of creating functions using the def
keyword with practical examples to help you master function definition and usage.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def
keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parentheses:
Example
def my_function():
print("Hello from a function")
my_function()
Output
Hello from a function
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (name
). When the function is called, we pass along a name, which is used inside the function to print a greeting:
Example
def my_function(name):
print("Hello, " + name)
my_function("Alice")
my_function("Bob")
my_function("Charlie")
Output
Hello, Alice
Hello, Bob
Hello, Charlie
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that is passed into a function.
From a function's perspective:
- A parameter is the variable listed inside the parentheses in the function definition.
- An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example
def my_function(first_name, last_name):
print(first_name + " " + last_name)
my_function("Alice", "Smith")
Output
Alice Smith
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This will an error as this function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Error Output
Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in
my_function("Emil")
TypeError: my_function() missing 1 required positional argument: 'lname'
Arbitrary Arguments, *args
If you do not know how many arguments will be passed into your function, add a *
before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
def my_function(*names):
print("The second name is " + names[1])
my_function("Alice", "Bob", "Charlie")
Output
The second name is Bob
Keyword Arguments
You can also send arguments with the key = value
syntax.
This way the order of the arguments does not matter.
Example
def my_function(child1, child2, child3):
print("The oldest child is " + child1)
my_function(child1 = "Alice", child2 = "Bob", child3 = "Charlie")
Output
The oldest child is Alice
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments will be passed into your function, add two asterisks: **
before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
Example
def my_function(**kid):
print("His last name is " + kid["last_name"])
my_function(first_name = "Charlie", last_name = "Brown")
Output
His last name is Brown
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without an argument, it uses the default value:
Example
def my_function(country = "USA"):
print("I am from " + country)
my_function("Canada")
my_function("India")
my_function()
my_function("Brazil")
Output
I am from Canada
I am from India
I am from USA
I am from Brazil
Passing a List as an Argument
You can send any data type of argument to a function (string, number, list, dictionary, etc.), and it will be treated as the same data type inside the function.
E.g. if you send a list as an argument, it will still be a list when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["kiwi", "pear", "peach"]
my_function(fruits)
Output
kiwi
pear
peach
Return Values
To let a function return a value, use the return
statement:
Example
def my_function(x):
return 7 * x
print(my_function(2))
print(my_function(4))
print(my_function(6))
Output
14
28
42
The pass Statement
Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass
statement to avoid getting an error.
Example
def my_function():
pass
Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments.
To specify that a function can have only positional arguments, add , /
after the arguments:
Example
def my_function(x, /):
print(x)
my_function(3)
Output
3
Keyword-Only Arguments
To specify that a function can have only keyword arguments, add *,
before the arguments:
Example
def my_function(*, x):
print(x)
my_function(x = 3)
Output
3
Combine Positional-Only and Keyword-Only
You can combine the two argument types in the same function.
Any argument before the /
, are positional-only, and any argument after the *
, are keyword-only.
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(2, 3, c = 5, d = 7)
Output
17
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
In this example, tri_recursion()
is a function that we have defined to call itself ("recurse"). We use the n
variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, the best way to find out is by testing and modifying it.
Example: Recursion
def tri_recursion(n):
if(n > 0):
result = n + tri_recursion(n - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(4)
Output
1
3
6
10