In programming, functions are pivotal tools for breaking down complex problems into manageable tasks. Each function performs a specific job, contributing to the overall solution. In Python, the def
keyword is your gateway to creating functions that promote efficient, organized, and maintainable code. In this article, we will learn how to use Def function in Python to create user-defined functions.
Types of Functions
In Python, functions fall into two primary categories:
- Built-in Functions: These functions are readily available, accessible through various libraries.
- User-defined Functions: Tailored to meet specific requirements, these functions are created using the
def
keyword.
Syntax of the Def Function
The general syntax for using the `def` function in Python is as follows:
def function_name(parameters):
# Function body
return
def
is the keyword in Python to define a function that marks the beginning of a function declaration.function_name
is the identifier or name of your function.parameters
(optional) represent the parameters that can be passed from outside to the function. You can pass multiple parameters as input also. For multiple parameters, separate them by commas and enclose them in parentheses.return
(optional) is the keyword to specify the value thedef
function returns when invoked. If thedef
function doesn’t have areturn
, it implicitly returnsNone
.
Calling a Def function
To use a Def function in Python, invoke it by its name and pass the required arguments within parentheses. Arguments allow you to pass information to functions. You can define functions with parameters that receive these arguments.
Here’s a simple example demonstrating how we can call a function.
# Define a function named welcome with name as a parameter
def welcome(name):
print(f"Hey {name}! Welcome to Entechin")
# Call the welsome function with a string as an argument
welcome('David')
Output:
Hey David! Welcome to Entechin
We can also define a function with more than one argument as shown below:
#Define a function to calculate the area of a rectangle
def calculate_rectangle_area(length, width):
area = length * width
return area
# Call the function with specific values
length = 5
width = 3
area = calculate_rectangle_area(length, width)
# Print the result
print(f"The area of the rectangle with length {length} and width {width} is {area} square units.")
Output:
The area of the rectangle with length 5 and width 3 is 15 square units.
In discussions related to functions, we commonly use the terms “parameter” and “argument” interchangeably, but they possess distinct meanings in Python programming. Parameters are variables declared within the parentheses of a Def function definition, while arguments are the values passed to a function when it’s invoked.
Types of Arguments
Keyword arguments
In Python, keyword arguments are a way to pass arguments to a function by explicitly specifying the parameter names along with their values.
Consider the following example:
# Define a function with keyword arguments
def display_info(firstname, lastname, Age, PhoneNumber, EmployeeID):
info = f"Name: {firstname} {lastname}, Age: {Age}, Phone Number: {PhoneNumber}, Employee ID: {EmployeeID}"
print(info)
display_info(firstname="Eliza", lastname="Johnson", Age=30, PhoneNumber="555-123-4567", EmployeeID="EMP12345")
Output:
Name: Eliza Johnson, Age: 30, Phone Number: 555-123-4567, Employee ID: EMP12345
The keyword arguments allow you to provide arguments out of order and makes function calls more readable and self-explanatory.
Default arguments
Default arguments have predefined values and are used when no value is provided for that argument. Here’s an example:
def flower(flower, collection='water lily'):
print("Propagate plants in your garden this year : " + flower + ", "+ collection)
flower('Pothon')
flower('wandering jew', 'jade plant')
Output:
Propagate plants in your garden this year : Pothon, water lily
Propagate plants in your garden this year : wandering jew, jade plant
In the above example, a function flower
takes two parameters as input i.e., flower
and collection
, where collection
has a default value of ‘water lily’. You then call this function with different sets of arguments. When you call the function with only one argument such as ‘Pothon’ for the flower
parameter, the collection parameter takes the default value ‘water lily’. However, if you provide both arguments, the default value of collection
parameter gets updated to a new value specified in the argument.
Lets see another example for more clearer understanding:
# Define a function with keyword arguments
def display_info(firstname, lastname, Age=None, PhoneNumber=None, EmployeeID=None):
info = f"Name: {firstname} {lastname}"
if Age is not None:
info += f", Age: {Age}"
if PhoneNumber is not None:
info += f", Phone Number: {PhoneNumber}"
if EmployeeID is not None:
info += f", Employee ID: {EmployeeID}"
print(info)
# Call the function with different sets of keyword arguments
display_info(firstname="Alice", lastname="Johnson", Age=30)
display_info(firstname="Bob", lastname="Smith", PhoneNumber="555-123-4567")
display_info(firstname="Charlie", lastname="Brown", EmployeeID="EMP12345")
display_info(firstname="David", lastname="Lee", Age=28, PhoneNumber="555-987-6543", EmployeeID="EMP54321")
Output:
Name: Alice Johnson, Age: 30
Name: Bob Smith, Phone Number: 555-123-4567
Name: Charlie Brown, Employee ID: EMP12345
Name: David Lee, Age: 28, Phone Number: 555-987-6543, Employee ID: EMP54321
In this example, the display_info
function accepts multiple keyword arguments, including Age
, PhoneNumber
, and EmployeeID
. You can call this function with various combinations of these keyword arguments. The function constructs an information string based on the provided arguments and prints it. If any of the keyword arguments are not provided, their corresponding information is omitted from the output. This allows you to provide specific information while omitting others based on the context of the function call.
Variable-length arguments
Python allows functions to accept multiple arguments using the *args
and **kwargs
syntax. *args
receives multiple positional arguments as a tuple, while **kwargs
accepts multiple keyword arguments as a dictionary.
Lets see an example of a Python function that uses variable-length arguments (*args
) to calculate the average of a list of numbers:
def calculate_average(*args):
if len(args) == 0:
return 0 # Handle the case of an empty input
total = sum(args)
return total / len(args)
# Calculate the average of different sets of numbers
set1 = [10, 20, 30, 40, 50]
set2 = [2.5, 3.5, 4.5, 5.5]
set3 = [15]
average1 = calculate_average(*set1)
average2 = calculate_average(*set2)
average3 = calculate_average(*set3)
# Print the results
print(f"Average of set1: {average1}")
print(f"Average of set2: {average2}")
print(f"Average of set3: {average3}")
Output:
Average of set1: 30.0
Average of set2: 4.0
Average of set3: 15.0
In this example, the calculate_average
function takes a variable-length argument *args
, which allows you to pass any number of arguments to the function. Inside the function, it first checks if the input list (args
) is empty. If it’s empty, it returns 0 to avoid division by zero. Then, the function calculates the sum of all the numbers in the input list and divides it by the number of elements to compute the average. The function is called using the *
operator to unpack the elements of each set as arguments to the function. Finally, the averages are printed for each set.
The **kwargs
parameter allows you to pass a variable number of keyword arguments to a function. Keyword arguments are those that are passed with their names as keys and values. Following example demonstrates the use of **kwargs parameter:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Julia Davis", age=30)
Output:
name: Julia Davis
age: 30
In summary, *args
deals with positional arguments and treats them as a tuple whereas **kwargs
deals with keyword arguments and treats them as a dictionary. You can use both *args
and **kwargs
in the same function definition, but *args
must appear before **kwargs
if both are used.
Return statement of Def functions
The return
statement allows you to pass results from a function back to the calling code and denotes the end of a function. Any code after the return statement does not execute. You can use multiple return
statements in a function to produce different results. Here is a simple example to show the working of a return statement:
import statistics
def variance_and_stddev(data):
# Calculate the variance
variance = statistics.variance(data)
# Calculate the standard deviation
standard_deviation = statistics.stdev(data)
return variance, standard_deviation
# Given data as a list
data = [22, 17]
# Call the function and unpack the results
variance, standard_deviation = variance_and_stddev(data)
print("The variance is:", variance)
print("The standard deviation is:", standard_deviation)
Output:
The variance is: 12.5
The standard deviation is: 3.5355339059327378
In this example, we have a function called variance_and_stddev
that accepts a single parameter, data
, which is a list containing the values ’22’ and ’17’. Within the function, the return
statement is employed to define the value to be returned. This value represents both the standard deviation and variance calculated for the numbers in the data
list. Lets see another example in which a user-defined function is created which explicitly returns the mean, mode and median values simultaneously.
import statistics as stat
def statistics_func(sample):
return stat.mean(sample), stat.median(sample), stat.mode(sample)
statistics_func([22,17])
Output:
(19.5, 19.5, 22)
Conclusion
In summary, Python functions are essential for creating organized and reusable code. Whether it’s simple arithmetic operations or complex data processing, Python functions are your go-to tools for efficient programming. This article has explored various aspects of Python functions, from their syntax to the distinction between parameters and arguments, and different types of arguments. The primary method for defining functions is by using the def
keyword which allows you to specify parameters and define the function’s logic. The function’s body can contain various logical instructions. We’ve also covered the versatile return statement. With these insights, you’re well-equipped to write Python functions for a wide range of tasks. Happy coding!
For any queries, contact us.