Python Function
A function is a reusable block of code that performs a specific task. Instead of writing the same code repeatedly, you can place it inside a function and call it whenever needed. This keeps your code clean, organized, and easy to maintain.
Defining a Function
To define a function, you use the def keyword, give the function a name, add parantheses for any parameters, follow with a colon, and then write the indented block of code the function will execute.
For example:
def greet():
print("Hello, James!")
Basic Syntax of a Function
def function_name(parameters):
# code block
return result # Optional
def → keyword used to define a function.
function_name → name of the function.
parameters → values you pass into the function (optional).
: → indicates the start of the function block.
Indented code block → the body of the function; contains the statements that run when the function is called.
return → sends a value back to the caller (optional).
Calling a Function
To call a function, write the function’s name followed by parentheses, placing any required arguments inside the parentheses.
For example:
def greet():
print("Hello, Welcome to LivingWithCode.com!")
greet() # Output: # Hello, Welcome to LivingWithCode.com!
Function With Parameters
Parameters allow your function to accept input values, providing the function with input data it needs to perform its task.
For example:
def greet(name):
print(f"Hello, {name}!")
greet("James")
greet("Rock")
greet("Justin")
Output:
Hello, James!
Hello, Rock!
Hello, Justin!
Parameters Vs Arguments
In Python functions, the terms parameters and arguments are often used interchangeably, but there is a subtle difference between them.
- A parameter is a variable defined within the parentheses in the function definition (e.g.,
nameindef greet(name):). - An argument is the actual value passed to the function when it is called (e.g.,
"James"ingreet("James")).
Types of Function Arguments
Here is a clear overview of the different ways you can pass arguments to a function:
(1) Positional Arguments
Positional arguments are matched to function parameters by their order in the function call.
For example:
def greet(name, age):
print(f"My name is {name} and i am {age} years old.")
greet("James", 30) # Output: My name is James and i am 30 years old.
In this example, the function greet() has two parameters, name and age. By default, Python uses positional arguments, which means the values you pass are assigned based on their order. The first value in the function call goes to name, and the second goes to age. So when you call greet("James", 30), "James" is assigned to name and 30 to age. The function then uses these values to print the message.
(2) Keyword Arguments
Keyword arguments lets you specify which value goes to which parameter by using the parameter’s name in the function call (e.g., name="James", age=30). With keyword arguments, the order of arguments doesn’t matter.
For example:
def greet(name, age):
print(f"My name is {name} and i am {age} years old.")
greet(age=30, name="James") # Output: My name is James and i am 30 years old.
In this example, the function call uses keyword arguments, so each value is assigned directly to its corresponding parameter. When you call greet(age=30,name="James" ), Python assigns 30 to age and "James" to name . The function then uses these values to print the message.
(3) Default Arguments
You can assign default values to parameters when defining a function. If you don’t provide values for those arguments when calling the function, the default values are used.
For example:
def greet(name, age=20):
print(f"My name is {name} and I am {age} years old.")
greet("David") # Output: My name is David and I am 20 years old.
greet("James", 30) # Output: My name is James and I am 30 years old.
IN this example, we have defined the greet() function with a default value of 20 for the age parameter. This means that when we call the greet() function without providing the value for age parameter, Python automatically uses the default value of 20.
(4) Arbitrary Keyword Arguments
Sometimes you don’t know ahead of time what extra arguments a caller might pass, and that’s where *args and **kwargs comes in handy. They let your function accept any number of extra arguments without you having to define them explicitly.
(a) *args
It allows a function to accept any number of positional arguments. The arguments passed to *args are collected into a tuple inside the function.
For example:
def user_info(*details):
print(details)
user_info("James", 30, "London")
Output:
('James', 30, 'London')
You can easily loop through a tuple using a for loop and handle each piece of user information individually. In the example below, I have iterated through the details tuple and printed each item separately.
def user_info(*details):
for i in details:
print(i)
user_info("James", 30, "London")
Output:
James
30
London
(b) **kwargs
It allows a function to accept any number of keyword arguments. The keyword arguments are collected into a dictionary inside the function.
For example:
def user_info(**details):
print(details)
user_info(name="James", age=30, location="London")
Output:
{'name': 'James', 'age': 30, 'location': 'London'}
Similarly, you can easily loop through a dictionary using a for loop to handle each piece of user information individually. In the example below, I have iterated through though the dictionary and printed each piece of information separately.
def user_info(**details):
for k, v in details.items():
print(f"{k}: {v}")
user_info(name="James", age=30, location="London")
Output:
name: James
age: 30
location: London
Mixing Different Arguments
In Python, you can mix different types of arguments when calling a function, which makes calling the function more flexible. However, they must follow a specific order in the function definition:
- Positional arguments
*args- Keyword arguments
- Default arguments
**kwargs
Mixing Positional and Default Arguments
When mixing positional and default arguments, always pass the positional arguments first. Any arguments that have default values, should be passed after positional arguments, either in the correct order or explicitly using their names.
For example:
def user_info(name, age, location="Unknown"):
print(name)
print(age)
print(location)
user_info("James", 30, "London")
Output:
James
30
London
You can also call the user_info() function by explicitly naming the default argument:
user_info("James", 30, location="London")
This function call produces the same output as the previous example.
Mixing Positional and Keyword Arguments
When mixing positional and keyword arguments, ensure that keyword arguments always come after the positional arguments.
For example:
def user_info(name, age, location):
print(name)
print(age)
print(location)
user_info("James", age="30", location="London")
Output:
James
30
London
Mixing Positional and Arbitrary Arguments
Similarly, when mixing positional arguments with arbitrary arguments (such as *args and *kwargs), the positional argument must come first, followed by arbitrary ones.
For example:
def user_info(name, age, *other):
print(name)
print(age)
print(other)
user_info("James", 30, "London", "Oxford Street")
Output:
James
30
('London', 'Oxford Street')
The same rule applies when arbitrary keyword arguments (**kwargs) are used.
def user_info(name, age, **other):
print(name)
print(age)
print(other)
user_info("James", 30, city="London", street="Oxford Street")
Output:
James
30
{'city': 'London', 'street': 'Oxford Street'}
Combining All Arguments
You can combine different types of arguments in a single function call, but remember the order of arguments we discussed earlier.
For example:
def complex_function(pos1, pos2, *args, kwarg1, kwarg2="default", **kwargs):
print(f"Positional: {pos1}, {pos2}")
print(f"Args: {args}")
print(f"Keyword: {kwarg1}")
print(f"Keyword (default): {kwarg2}")
print(f"Kwargs: {kwargs}")
complex_function("A", "B", 1, 2, 3, kwarg1="custom", extra1=10, extra2=20)
Output:
Positional: A, B
Args: (1, 2, 3)
Keyword: custom
Keyword (default): default
Kwargs: {'extra1': 10, 'extra2': 20}
Return Values
Python functions doesn’t always have to print their output. Instead, they can return values after performing an operation, allowing the result to be stored in a variable or other parts of the program for further use.
You use the return statement to return values from the function.
For example:
def add(a, b):
result = a + b
return result
sum_result = add(2, 3)
print(sum_result) # Output: 5
In this example, the add() function accepts two parameter a and b. When the function is called with the arguments 2 and 3, these two numbers are added and the result is stored in the variable result. The function then returns this value using the return value. The returned value is assigned to the variable sum_result, which is printed to the screen, producing the output 5.
You can also perform the operation directly in the return statement.
def add(a, b):
return a + b
sum_result = add(2, 3)
print(sum_result) # Output: 5
Returning Multiple Values
A function can return multiple values by returning them as a tuple. This happens automatically when you separate return values with commas.
For example:
def calculate(a, b):
total = a + b
difference = a - b
return total, difference # returns a tuple
result = calculate(5, 2)
print(result) # Output: (7, 3)
You can easily unpack the returned tuple values as follows:
def calculate(a, b):
total = a + b
difference = a - b
return total, difference # return a tuple
# Call the function and unpack the returned tuple into two variables
sum_value, diff_value = calculate(5, 2)
print(sum_value) # Output: 7
print(diff_value) # Output: 3
Function Without a Return Statement
If a function doesn’t have a return statement, it returns None by default.
For example:
def greet(name):
print(f"Hello, {name}!") # Print a greeting message to the given name
# Call the function and store the result
result = greet("James") # This prints "Hello, James!" but returns None
print(result) # Output: None
In this example, the greet() function doesn’t have a return statement, so Python returns None by default.
The pass Statement
When you define a function, the body cannot be empty – Python raises an error if it is. However, if you want to define a function and implement it later, you can use the pass statement. This allows the function to exist without doing anything for now.
For example:
def calculate(a, b):
pass