Functions are one of the fundamental building blocks in Python. They allow you to encapsulate reusable pieces of code and improve modularity and code organization. Defining functions with parameters of different types and return values is a common practice in Python programming.
This guide will provide a practical overview of using functions with different parameter types like positional, keyword, default, variable-length, and more. We will also cover examples of functions that return values of various data types like strings, numbers, lists, dictionaries, etc.
Understanding parameter passing and return values is essential to writing cleaner, more modular Python code. The examples and explanations in this guide will help you learn these function concepts in a hands-on manner. Let’s get started!
Table of Contents
Open Table of Contents
Positional Parameters
Positional parameters allow you to pass arguments to a function based on the order in which they are defined in the function signature.
Here is an example function that calculates the area of a rectangle using two positional parameters - length and breadth:
def calculate_area(length, breadth):
area = length * breadth
return area
rectangle_area = calculate_area(4, 5)
print(rectangle_area)
# Output: 20
The length
and breadth
parameters are positional - their order matters during function calls. The values 4 and 5 are passed to length
and breadth
respectively based on the position.
Positional parameters enable you to write functions that accept inputs in a defined, ordered way.
Keyword Parameters
Keyword parameters allow you to pass arguments to a function by the parameter name, without worrying about the order.
Here’s an example:
def calculate_area(length, breadth):
area = length * breadth
return area
# Call function using keyword arguments
rectangle_area = calculate_area(breadth=5, length=4)
print(rectangle_area)
# Output: 20
By using keywords length
and breadth
during the function call, the order does not matter anymore. The values get mapped to the right parameter names.
Keyword parameters provide more readability, especially when a function has many parameters.
Default Parameters
Default parameters allow you to assign a default value to a parameter in the function definition. If no argument is passed for that parameter, the default value is used.
def calculate_area(length, breadth=2):
area = length * breadth
return area
# Calculate area with default breadth
rectangle_area = calculate_area(4)
print(rectangle_area)
#Output: 8
# Calculate area by passing breadth value
rectangle_area = calculate_area(4, 5)
print(rectangle_area)
#Output: 20
By setting breadth
to default to 2, we can call the function without passing the breadth
value - it will take 2 by default.
Default parameters are useful when a parameter has a standard default that doesn’t need to be passed frequently.
Variable-length Parameters
Unlike positional and default parameters, variable-length parameters allow you to pass an arbitrary number of arguments to a function. The *args
syntax is commonly used for this.
def calculate_areas(*lengths, breadth):
areas = []
for length in lengths:
area = length * breadth
areas.append(area)
return areas
rect_areas = calculate_areas(2, 4, 5, 6, breadth=5)
print(rect_areas)
# Output: [10, 20, 25, 30]
The *lengths
parameter gathers all positional arguments passed during the function call into a tuple named lengths
. This allows accepting and looping through any number of length
values.
Variable-length parameters provide flexibility when the number of arguments is not fixed beforehand.
Keyword Variable-length Parameters
We can also use the **kwargs
syntax to accept an arbitrary number of keyword arguments.
def print_student_data(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
print_student_data(name="John", age=20, hobbies=["football", "chess", "hiking"])
# Output:
# name = John
# age = 20
# hobbies = ['football', 'chess', 'hiking']
The **kwargs
collects all keyword arguments passed to the function into a dictionary. We can loop through and print each key: value
pair.
This technique is common when writing flexible functions that accept variable user-supplied data.
Parameter Unpacking
Parameter unpacking allows you to unpack iterables like lists, tuples, and dictionaries into separate function parameters using the * and ** operators.
For example:
coordinates = [(2, 3), (5, 7), (9, 1)]
for x, y in coordinates:
print(f"X: {x}, Y: {y}")
# Output:
# X: 2, Y: 3
# X: 5, Y: 7
# X: 9, Y: 1
Here, the (x, y)
tuple gets unpacked into separate x
and y
parameters for each iteration.
We can similarly unpack dictionaries:
def display_student(**kwargs):
print(f"Name: {kwargs['name']}")
print(f"Age: {kwargs['age']}")
print(f"Major: {kwargs['major']}")
student = {'name': 'John', 'age': 20, 'major': 'Computer Science'}
display_student(**student)
# Output:
# Name: John
# Age: 20
# Major: Computer Science
The **student
unpacks the dictionary into separate keyword arguments.
Unpacking iterables allows passing them easily as function arguments.
Returning Values
The return statement is used to return a value from the function back to the caller. The returned value can be stored in a variable or used in an expression.
Here are some examples of functions returning commonly used data types:
Returning a string
def format_name(first, last):
full_name = f"{first} {last}"
return full_name
name = format_name("John", "Doe")
print(name)
# Output: John Doe
Returning a number
from math import pi
def calculate_circle_area(radius):
area = pi * radius * radius
return area
circle_area = calculate_circle_area(5)
print(round(circle_area, 2))
# Output: 78.54
Returning a list
def get_multiples(number, limit):
multiples = []
for i in range(1, limit+1):
multiples.append(number * i)
return multiples
nums = get_multiples(7, 5)
print(nums)
# Output: [7, 14, 21, 28, 35]
Returning a dictionary
def create_student(name, age, major):
student = {
'name': name,
'age': age,
'major': major
}
return student
john = create_student('John Doe', 20, 'Computer Science')
print(john)
# Output: {'name': 'John Doe', 'age': 20, 'major': 'Computer Science'}
The return value gets assigned to the name
, circle_area
, nums
, john
variables after function calls.
Return values allow the caller to further operate on the output of a function.
Real-World Examples
Let’s now look at some real-world examples of using functions with different parameter types and return values.
A BMI Calculator
Here is a calculate_bmi
function that uses positional and keyword arguments along with default values:
def calculate_bmi(weight, height, metric=True):
if metric:
bmi = weight / (height ** 2)
else:
bmi = 703 * (weight / (height ** 2))
return bmi
# Metric BMI
metric_bmi = calculate_bmi(weight=70, height=1.69)
print(metric_bmi)
# Output: 24.49
# Imperial BMI
imperial_bmi = calculate_bmi(weight=150, height=5.6, metric=False)
print(imperial_bmi)
# Output: 26.88073394495413
Finding the Highest Number
This function uses *args
to accept any number of arguments and returns the highest:
def find_max(*nums):
highest = float("-inf")
for num in nums:
if num > highest:
highest = num
return highest
max_num = find_max(4, 55, 2, -9, 100)
print(max_num)
# Output: 100
Parsing Key-Value Pairs
We can parse a string of key-value pairs into a dictionary using **kwargs
:
def parse_kv_pairs(**kwargs):
return kwargs
pairs = "name=John,age=20,major=Computer Science"
kv_dict = parse_kv_pairs(**pairs.split(','))
print(kv_dict)
# Output: {'name': 'John', 'age': '20', 'major': 'Computer Science'}
The real-world examples highlight how various parameter techniques and return values help write reusable and practical functions.
Summary
To recap, here are some key takeaways:
- Positional and keyword parameters allow passing arguments in different ways.
- Default and variable-length parameters provide flexibility when defining functions.
- Parameter unpacking lets you unpack iterables into separate parameters.
- Return values enable functions to return meaningful outputs.
- Functions can return strings, numbers, lists, dictionaries, or other objects.
- Real-world examples like BMI calculators and finding highest numbers demonstrate the usefulness of parameters and return values.
Learning function parameters and return values is crucial for expertly organizing, reusing, and structuring code in Python. This guide covered practical examples of different parameter types and return value usage. Use these learnings to write clean, readable, and maintainable functions in your own Python code.