
Functions
A function is a reusable block of code that performs specific set of tasks. Functions allow you to break your program into smaller, manageable pieces, making your code more organized, readable, and maintainable.
Create a Function
To define a function, the def
keyword is used and followed by the function name and parentheses.
# Create a function named "greeting"def greeting(): print(f"Hello, world!")
In the example above, we created a function greeting
. Once defined, we can call this function to observe its behavior.
Call a Function
Calling a function runs the code it contains.
To call a function, use the function name followed by parenthesis:
# Call the greeting functiongreeting()
Output:
Hello, world!
Calling the greeting
function returns "Hello, world!
Arguments/Parameters
We can pass values into functions as arguments.
In the following example, we modify the greeting
function to accept a name
parameter, allowing it to print personalized greeting messages based on the provided argument.
# Modify the greeting function to accept a "name" parameterdef greeting(name): print(f"Hello, {name}!")
Then call the greeing function:
# Call the greeting functiongreeting(name="Alice")
Output:
Hello, Alice!
The value "Alice" is passed to the name
parameter, and the print
method uses this value to generate the output accordingly.
Let's see more examples.
Example of Creating a Summation Function
We'll create a function called add
that accepts two arguments, sums them, and prints the result.
# Create a function named "add"def add(a, b): # Sum up a and b result = a + b # Print the sum of a and b print(result)
Call the add function:
# Call the "add()" function with argumentsadd(a=5, b=3)
Output:
8
Calling the function with a=5
and b=3
returns the sum, 8.
Keyword Arguments and Positional Arguments
Keyword arguments
Keyword arguments are passed to a function with a specific keyword and associated value. This allows you to pass arguments to a function out of order, as long as you specify the parameter name.
Positional arguments
Positional arguments are passed to a function based on their position or order in the function call. The order in which arguments are passed determines which parameter they will be assigned to in the function definition.
In the function add()
, a=5
and b=3
are keyword arguments, identified by parameter names (a
and b
) followed by an equal sign =
and their values. Conversely, passing values as 5
and 3
without parameter names makes them positional arguments:
# Pass positional arguments to the add() functionadd(5, 3)
Output:
8
The function assigns positional arguments to parameters sequentially: 5 to a
and 3 to b
.
It is important to note that when using keyword arguments, they must be positioned after any positional arguments to prevent syntax errors. For instance, placing a keyword argument a=5
before a positional argument 3
results in a syntax error:
# Keyword arguments can't be placed before positional argumentsadd(a=5, 3)
Output:
add(a=5, 3) ^SyntaxError: positional argument follows keyword argument
It is appropriate to use positional arguments before keyword argument:
# Place positional arguments before keyword argumentsadd(5, b=3)
Output:
8
*args
and **kwargs
In Python, *args
and **kwargs
are special syntax used in function definitions to allow a function to accept a varying number of positional arguments and keyword arguments, respectively.
*args
When you define a function with *args
, you can pass any number of positional arguments to that function, and they will be collected into a tuple. The * symbol is used to pack the arguments into a tuple within the function.
Here's an example:
# Create a function with *argsdef my_function(*args): # Print the variable "args" print(args)
# Use a for loop to iterate elements in the args tuple for value in args: print(value)
my_function(1, 2, 3, 4)
Output:
(1, 2, 3, 4)
1
2
3
4
The my_function(*args)
function enables the acceptance of any number of positional arguments through the use of *args
. In this specific example, 1, 2, 3, 4
represent the positional arguments. They are then gathered and stored as a tuple within the variable args
.
**kwargs
When you define a function with **kwargs
, you can pass any number of keyword arguments to that function, and they will be collected into a dictionary. The **
symbol is used to pack the keyword arguments into a dictionary within the function.
Here's an example:
# Create a function with **kwargsdef my_function(**kwargs): # Print the variable "kwargs" print(kwargs)
# Use .items() function to access key-values pairs in the kwargs dictionary for key, value in kwargs.items(): print(f"{key}: {value}")
my_function(a=1, b=2, c=3)
Output:
{'a': 1, 'b': 2, 'c': 3}
a: 1
b: 2
c: 3
The my_function(**kwargs)
function accepts an unlimited number of keyword arguments through the use of **kwargs
. In this example, a=1, b=2, c=3
are keyword arguments, compiled into a dictionary stored in kwargs
variable, where parameter names become dictionary keys and their corresponding values become dictionary values.