Day 7: Functions & Modules (Part II) + Review
Today we’ll build on what you learned in Day 6 by deepening your understanding of functions and
modules. We'll review key concepts and explore some advanced function topics that make your
code even more flexible and powerful.
Step 1: Quick Review of Day 6
Functions Recap
• Defining a Function:
Use def to define a block of code that can be reused.
def greet():
print("Hello!")
greet()
• Parameters, Arguments, and Return Values:
Functions can accept parameters and return results.
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5
• Default and Keyword Arguments:
Provide default values and use keyword arguments for clarity.
def introduce(name="Guest", age=0):
print(f"My name is {name} and I am {age} years old.")
introduce()
introduce(name="Alice", age=28)
Modules Recap
• Importing Modules:
Leverage Python’s standard library or your own modules.
import math
print("Square root of 16 is", math.sqrt(16))
• Creating Your Own Module:
Save functions in a separate file (e.g., mymodule.py) and import them.
# In mymodule.py:
def multiply(a, b):
return a * b
# In your main script:
import mymodule
print("Product:", mymodule.multiply(4, 5))
Step 2: Advanced Function Topics
A. Variable Length Arguments
Using *args for Positional Arguments:
• Purpose: Allow a function to accept an arbitrary number of positional arguments.
• Example:
def greet_all(*names):
for name in names:
print("Hello,", name)
greet_all("Alice", "Bob", "Charlie")
Using **kwargs for Keyword Arguments:
• Purpose: Accept an arbitrary number of keyword arguments (as a dictionary).
• Example:
def print_pet_info(**pet):
for key, value in pet.items():
print(f"{key}: {value}")
print_pet_info(name="Buddy", species="Dog", age=5)
B. Lambda Functions
• Definition:
A lambda function is a small, anonymous function defined with the lambda keyword. It’s
ideal for short, one-line functions.
• Example:
square = lambda x: x * x
print("Square of 5:", square(5))
C. Map, Filter, and Reduce
• Map:
Apply a function to every item in an iterable.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print("Squares:", squares)
• Filter:
Select items from an iterable that satisfy a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
• Reduce:
Apply a rolling computation to sequential pairs of values in an iterable (requires importing
from functools).
from functools import reduce
total = reduce(lambda x, y: x + y, numbers)
print("Total:", total)
D. (Optional) Introduction to Decorators
• Definition:
Decorators are functions that modify the behavior of other functions.
• Example:
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@simple_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
Note: Decorators are an advanced topic. Feel free to explore them further when you’re comfortable
with the basics.
Step 3: Module Review & Advanced Usage
Creating and Using Your Own Modules
• Recap:
Save related functions in a file and import them in your script.
• Example:
1. Create mymath.py:
# mymath.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
2. Use the Module:
import mymath
print("Addition:", mymath.add(2, 3))
print("Multiplication:", mymath.multiply(2, 3))
• Action:
Visit the Python Standard Library documentation for more details.
Step 4: Hands-On Exercises
Exercise 1: Sum with Variable Length Arguments
• Task:
Write a function that accepts any number of numerical arguments and returns their sum.
• Sample Code:
def sum_all(*numbers):
return sum(numbers)
print("Sum of 1, 2, 3 is:", sum_all(1, 2, 3))
Exercise 2: Create and Import Your Own Module
• Task:
Create a module called string_utils.py with a function to reverse a string. Then, import and
use that function in another script.
• Sample Code:
string_utils.py:
def reverse_string(s):
return s[::-1]
Main script:
import string_utils
print("Reversed 'hello':", string_utils.reverse_string("hello"))
Exercise 3: Lambda and Filter
• Task:
Use a lambda function with filter to create a new list containing only even numbers from a
given list.
• Sample Code:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
Step 5: Experiment in the Python Interactive Shell
1. Open the Shell:
In your terminal, type:
python
2. Try Out Some Commands:
# Testing variable length arguments
def test_args(*args):
print("Arguments received:", args)
test_args(10, 20, 30)
# Testing lambda with map
numbers = [1, 2, 3, 4]
print("Doubled numbers:", list(map(lambda x: x * 2, numbers)))
# Testing **kwargs
def test_kwargs(**kwargs):
print("Keyword arguments:", kwargs)
test_kwargs(a=1, b=2, c=3)
3. Exit the Shell:
exit()
Step 6: Additional Learning Resources
• Python Official Documentation – Defining Functions:
Defining Functions