Python_7
Python_7
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.
Functions Recap
• Defining a Function:
Use def to define a block of code that can be reused.
def greet():
print("Hello!")
greet()
return a + b
result = add(2, 3)
print(result) # Output: 5
introduce()
introduce(name="Alice", age=28)
Modules Recap
• Importing Modules:
Leverage Python’s standard library or your own modules.
import math
# In mymodule.py:
import mymodule
• Example:
def greet_all(*names):
print("Hello,", name)
• Example:
def print_pet_info(**pet):
print(f"{key}: {value}")
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
• Map:
Apply a function to every item in an iterable.
numbers = [1, 2, 3, 4, 5]
print("Squares:", squares)
• Filter:
Select items from an iterable that satisfy a condition.
numbers = [1, 2, 3, 4, 5, 6]
• Reduce:
Apply a rolling computation to sequential pairs of values in an iterable (requires importing
from functools).
print("Total:", total)
• Definition:
Decorators are functions that modify the behavior of other functions.
• Example:
def simple_decorator(func):
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.
• Recap:
Save related functions in a file and import them in your script.
• Example:
1. Create mymath.py:
# mymath.py
return a + b
return a * b
import mymath
• Action:
Visit the Python Standard Library documentation for more details.
• 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))
• 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
• 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]
python
def test_args(*args):
numbers = [1, 2, 3, 4]
print("Doubled numbers:", list(map(lambda x: x * 2, numbers)))
# Testing **kwargs
def test_kwargs(**kwargs):
exit()