Understanding Python Functions
A function in Python is essentially a block of organized, reusable code that performs a single action. Functions provide a way to organize and manage code efficiently, reducing repetition and enhancing readability.
Functions are executed only when called, and they can accept data inputs known as parameters. They can also return data as output, making them versatile tools in programming.
Defining a Function
To define a function in Python, use the def
keyword followed by the function name and parentheses:
def my_function():
print("Hello from a function")
Calling a Function
Once a function is defined, it must be called to execute. You can do this by using the function’s name followed by parentheses:
def my_function():
print("Hello from a function")
my_function()
Passing Arguments
Functions can accept data inputs, called arguments. These are specified within the parentheses after the function name. You can pass multiple arguments by separating them with commas:
def my_function(book):
print(book + " is a great read")
my_function("Python Programming")
my_function("Data Science with Python")
my_function("Artificial Intelligence")
In Python documentation, arguments are often referred to as args.
Parameters vs Arguments
Though often used interchangeably, the terms “parameter” and “argument” have distinct meanings. A parameter is the variable listed inside the parentheses in the function definition, while an argument is the value passed to the function when it is called.
Handling Multiple Arguments
By default, you must provide the exact number of arguments that a function expects. If a function expects two arguments, you need to provide exactly two:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Jane", "Doe")
If you call the function with an incorrect number of arguments, an error will occur.
Arbitrary Arguments (*args)
If you are unsure about the number of arguments that will be passed into a function, you can use an asterisk (*
) before the parameter name. This allows the function to receive a tuple of arguments:
def my_function(*books):
print("The last book I read was " + books[-1])
my_function("Python Basics", "Deep Learning", "Machine Learning")
In Python documentation, arbitrary arguments are often referred to as *args.
Keyword Arguments
Python also allows you to pass arguments using the key = value
syntax, which makes the order of arguments irrelevant:
def my_function(book1, book2, book3):
print("The first book I read was " + book1)
my_function(book1 = "Python 101", book2 = "Data Science", book3 = "AI Mastery")
Keyword arguments are often referred to as kwargs in Python documentation.
Arbitrary Keyword Arguments (**kwargs)
If you are unsure about the number of keyword arguments that will be passed into a function, use a double asterisk (**
) before the parameter name. This allows the function to receive a dictionary of arguments:
def my_function(**book_info):
print("The author's last name is " + book_info["lname"])
my_function(fname = "Jane", lname = "Doe")
Arbitrary keyword arguments are often shortened to **kwargs in Python documentation.
Default Parameter Value
You can set a default value for a parameter, which will be used if no argument is provided during the function call:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
Passing a List as an Argument
Any data type can be passed as an argument to a function, including lists. When you pass a list, it remains a list within the function:
def my_function(books):
for book in books:
print(book)
reading_list = ["Python Crash Course", "Fluent Python", "Learning Python"]
my_function(reading_list)
Returning Values
Functions can return values using the return
statement:
def multiply_by_five(x):
return 5 * x
print(multiply_by_five(3))
print(multiply_by_five(5))
print(multiply_by_five(9))
The pass Statement
If you define a function but don’t want to add any code to it yet, use the pass
statement to avoid errors:
def placeholder_function():
pass
Positional-Only Arguments
In Python, you can specify that a function accepts only positional arguments by adding a slash (/
) after the arguments:
def my_function(x, /):
print(x)
my_function(3)
Without the slash, you could use keyword arguments even if the function expects positional arguments:
def my_function(x):
print(x)
my_function(x = 3)
Keyword-Only Arguments
To enforce that a function accepts only keyword arguments, add an asterisk (*
) before the arguments:
def my_function(*, x):
print(x)
my_function(x = 3)
Combining Positional-Only and Keyword-Only Arguments
You can combine positional-only and keyword-only arguments within the same function:
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
Recursion in Functions
Python supports recursion, which allows a function to call itself. Recursion is a powerful technique often used in algorithms and mathematical calculations. However, it requires careful implementation to avoid infinite loops and excessive resource consumption:
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\nRecursion Example Results")
tri_recursion(6)
Recursion can be challenging to understand initially, but experimenting with it is the best way to learn how it works.
Test Yourself with Exercises
Exercise: Create a function named my_function
that prints “Hello from a function”.