Functions in Python - Part 2
Working with Functions in Python
Arguments vs Parameters
Parameters:
Parameters are variables or placeholders defined in the function's declaration (or definition). They are used to specify what kind of values a function expects to receive when it is called.
Parameters act as a way to pass data into a function. They define the input requirements for the function.
Parameters are typically listed in the function's signature within the parentheses.
Arguments:
Arguments, on the other hand, are the actual values or expressions that are passed into a function when it is called. These values are provided to match the parameters of the function.
Arguments are the real data that gets passed to the function to be processed or used within the function's code.
When you call a function, you pass arguments to it, which correspond to the parameters defined in the function's signature.
def my_func(a,b):
#code here
x = 10
y = 'a'
my_func(x,y)
In this context above a,b are the called parameters of my_func. Also note that a and b are variables local to my_func . a,b are called as parameters of the fuction where are x and y are called as arguments. Also note that x and y are passed by reference. i.e the memory addresses of x and y are passed.
Positional Arguments
Positional arguments are a type of function argument where the order and position of the arguments matter. When we define a function with parameters, the values we pass to the function when calling it are matched to the parameters based on their position. Positional arguments are the most common type of arguments in Python functions.
def my_func(a,b):
#code here
my_func(10,20) => a = 10 and b = 20
my_func(20,10) => a = 20 and b = 10
Default Values
Positional arguments can be made optional in Python by specifying default values for the corresponding parameters in the function's definition. When we provide default values for parameters, those values are used if the caller of the function does not provide an argument for that parameter.
def my_func(a,b=100):
#code here
my_func(10,20) => a = 10 and b = 20
my_func(5) => a = 5 and b = 100
def my_func(a, b=5, c=10):
#code here
my_func(1) โ a = 1, b = 5, c = 10
my_func(1, 2) โ a = 1, b = 2, c = 10
my_func(1, 2, 3) โ a = 1, b = 2, c = 3
But what if we want to specify the 1st and 3rd arguments, but omit the 2nd argument?
In Python, if we want to specify the 1st and 3rd arguments while omitting the 2nd argument, we can do so by using named arguments (also known as keyword arguments). Named arguments allow you to specify which parameter each value should be assigned to by using the parameter's name. This way, we can skip providing a value for a specific parameter and only provide values for the parameters you want.
In Python, we can specify positional arguments by using the parameter names, regardless of whether the parameters have default values. This flexibility allows us to explicitly specify which argument corresponds to which parameter, even if the parameters have default values.
def my_func(a, b, c):
#code here
my_func(1, 2, 3)
my_func(1, 2, c=3)
my_func(a=1, b=2, c=3)
my_func(c=3, a=1, b=2)
a=1, b=2, c=3
In Python, once we use a named argument (keyword argument) in a function call, all the arguments that follow it must also be named. This rule ensures that there is no ambiguity in mapping values to parameters.
def my_func(a, b=2, c=3):
#code here
my_func(1) โ a=1, b=2, c=3
my_func(a=1, b=5) โ a=1, b=5, c=3
my_func(c=0, a=1) โ a=1, b=2, c=0
Unpacking Iterables
In Python, "packed values" usually refer to values that are bundled together in a data structure like tuples, lists, or dictionaries. These data structures allow you to store multiple values in a single container.
Tuples: A tuple is an ordered, immutable collection of values. You can pack different types of values into a tuple. For example:
person = ("John", 30, "Male")
Here, we've packed three values into a tuple representing a person's name, age, and gender.
Lists: Lists are ordered, mutable collections of values. You can pack values of any type into a list:
numbers = [1, 2, 3, 4, 5]
In this case, we've packed a sequence of numbers into a list.
Dictionaries: Dictionaries in Python allow you to pack key-value pairs together:
student = {"name": "Alice", "age": 22, "grade": "A"}
This dictionary packs information about a student with keys like "name," "age," and "grade."
Strings: Even a string is considered to be a packed value
These are just a few examples of how values can be packed in Python. The choice of data structure depends on your specific use case and requirements. Packed values make it easier to work with related data and can be accessed, modified, and iterated over conveniently.
Unpacking in Python refers to the process of splitting or extracting values from packed data structures like lists or tuples and assigning them to individual variables. This allows you to work with the individual elements more conveniently. Here are some examples:
Tuple Unpacking:
person = ("John", 30, "Male") name, age, gender = person
In this example, we have a tuple
person
, and we unpack its values into the variablesname
,age
, andgender
.List Unpacking:
numbers = [1, 2, 3, 4, 5] first, second, *rest = numbers
Here, we unpack the first two elements of the list into
first
andsecond
, and the rest of the elements are packed into therest
list using the*
operator.Dictionary Unpacking:
student = {"name": "Alice", "age": 22, "grade": "A"} name, age, grade = student.values()
In this case, we unpack the values of a dictionary into individual variables.
Unpacking is a powerful feature in Python that makes it easy to work with structured data and simplifies the assignment of values to variables. It's often used in functions that return multiple values or when processing data in loops and comprehensions.
In conclusion, understanding the differences between arguments and parameters, as well as mastering the use of positional and keyword arguments, is crucial for writing efficient and flexible Python functions. Additionally, unpacking iterables is a powerful technique that simplifies working with structured data, making it easier to assign values to variables and process data in loops and comprehensions. By applying these concepts, you can enhance your Python programming skills and create more effective code.
Practice Use case:
Calculator: Build a simple command-line calculator program that can perform addition, subtraction, multiplication, and division.
Calculate Factorial: Write a function that calculates the factorial of a given number using recursion.
Fibonacci Sequence: Implement a function that generates the Fibonacci sequence up to a given number of terms.
Matrix Operations: Write functions to perform basic matrix operations like addition, subtraction, and multiplication.
Guess the Number Game: Develop a number-guessing game where the computer generates a random number, and the player has to guess it using functions for game logic.
Recursive Directory Search: Implement a function that searches for a file with a specific name within a directory and its subdirectories recursively.