Day 03: Functions and Modules
π Table of Contents
- π Welcome to Day 3
- π§ Functions in Python
- Defining Functions
- Parameters and Return Values
- Scope and Lifetime
- Lambda Functions
- Recursive Functions
- π¦ Modules in Python
- Importing Modules
- Creating Your Own Modules
- Using Built-in Modules
- π Packages in Python
- Understanding Packages
- Creating and Importing Packages
- π» Hands-On Coding
- Example Scripts
- 𧩠Interactive Exercises
- π Resources
- π‘ Tips and Tricks
1. π Welcome to Day 3
Welcome to Day 3 of "Becoming a Scikit-Learn Boss in 90 Days"! π Today, we dive deep into Functions and Modules in Python. Mastering these concepts is essential for writing clean, reusable, and organized code, especially when working on complex machine learning projects. Let's enhance our coding skills and unlock the full potential of Python! π
2. π§ Functions in Python
Functions are fundamental building blocks in Python that allow you to encapsulate reusable pieces of code. They help in organizing code, improving readability, and reducing redundancy.
π Defining Functions
Syntax:
def function_name(parameters):
"""
Optional docstring
"""
# Function body
return value
Example:
def greet(name):
"""
Returns a greeting message for the given name.
"""
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
π Parameters and Return Values
Functions can accept parameters (arguments) and can return values using the return
statement.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
π Scope and Lifetime
Scope refers to the visibility of variables. Variables defined inside a function are local to that function, while variables defined outside are global.
Example:
x = 10 # Global variable
def foo():
y = 5 # Local variable
print(x) # Accessing global variable
print(y)
foo()
print(x)
# print(y) # This will raise a NameError
π Lambda Functions
Lambda functions are small anonymous functions defined using the lambda
keyword. They are useful for short, throwaway functions.
Example:
# Regular function
def square(x):
return x ** 2
# Lambda function
square_lambda = lambda x: x ** 2
print(square(4)) # Output: 16
print(square_lambda(4)) # Output: 16
π Recursive Functions
Recursive functions call themselves to solve smaller instances of a problem. They must have a base case to terminate the recursion.
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
3. π¦ Modules in Python
Modules are Python files containing functions, classes, or variables that you can include in your projects. They help in organizing code into manageable and reusable components.
π Importing Modules
You can import entire modules or specific functions/classes from a module.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
Importing Specific Functions:
from math import pi, sin
print(pi) # Output: 3.141592653589793
print(sin(pi / 2)) # Output: 1.0
π Creating Your Own Modules
To create your own module, simply save a Python file (e.g., math_utils.py
) with function definitions.
math_utils.py:
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero!"
return a / b
Using math_utils.py:
import math_utils
print(math_utils.multiply(4, 5)) # Output: 20
print(math_utils.divide(10, 2)) # Output: 5.0
print(math_utils.divide(10, 0)) # Output: Cannot divide by zero!
π Using Built-in Modules
Python comes with a rich set of built-in modules that you can use without installing anything.
Example:
import datetime
current_time = datetime.datetime.now()
print(current_time)
4. π Packages in Python
Packages are collections of modules organized in directories. They help in structuring large codebases and avoiding module name conflicts.
π Understanding Packages
A package is a directory containing an __init__.py
file and multiple modules.
Directory Structure:
my_package/
__init__.py
module1.py
module2.py
π Creating and Importing Packages
Creating a Package:
- Create a directory named
my_package
. - Inside
my_package
, create an__init__.py
file (can be empty). - Add your modules (
module1.py
,module2.py
, etc.).
Using the Package:
from my_package import module1, module2
module1.function_a()
module2.function_b()
Example:
my_package/module1.py:
def function_a():
print("Function A from Module 1")
my_package/module2.py:
def function_b():
print("Function B from Module 2")
main.py:
from my_package import module1, module2
module1.function_a() # Output: Function A from Module 1
module2.function_b() # Output: Function B from Module 2
5. π» Hands-On Coding
π Example Scripts
π Script 1: Advanced Calculator with Functions
# advanced_calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error! Division by zero."
return a / b
def main():
while True:
print("\n--- Advanced Calculator ---")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Thank you for using the calculator. Goodbye!")
break
if choice in ['1', '2', '3', '4']:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numeric values.")
continue
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
result = divide(num1, num2)
print(f"{num1} / {num2} = {result}")
else:
print("Invalid input! Please choose a valid operation.")
if __name__ == "__main__":
main()
π Script 2: Using Custom Modules
string_utils.py
# string_utils.py
def to_uppercase(s):
return s.upper()
def to_lowercase(s):
return s.lower()
main.py
# main.py
import string_utils
def main():
text = "Hello, World!"
print(string_utils.to_uppercase(text)) # Output: HELLO, WORLD!
print(string_utils.to_lowercase(text)) # Output: hello, world!
if __name__ == "__main__":
main()
6. 𧩠Interactive Exercises
π Exercise 1: Defining and Using Functions
-
Task: Define a function that calculates the area of a rectangle. The function should take length and width as parameters and return the area.
def calculate_area(length, width): return length * width # Example usage area = calculate_area(5, 3) print(f"The area is {area}") # Output: The area is 15
π Exercise 2: Scope of Variables
-
Task: Create a function that modifies a global variable. Observe the changes.
count = 10 # Global variable def increment(): global count count += 1 print(f"Inside function: {count}") increment() # Output: Inside function: 11 print(f"Outside function: {count}") # Output: Outside function: 11
π Exercise 3: Lambda Functions
-
Task: Create a lambda function that takes two numbers and returns their product. Use it to multiply two numbers.
multiply = lambda x, y: x * y result = multiply(4, 5) print(result) # Output: 20
π Exercise 4: Creating and Using Modules
-
Task: Create a module named
math_operations.py
with functionsadd
,subtract
,multiply
, anddivide
. Import this module into another script and use its functions.math_operations.py
# math_operations.py def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b == 0: return "Cannot divide by zero!" return a / b
main.py
# main.py import math_operations def main(): print(math_operations.add(10, 5)) # Output: 15 print(math_operations.subtract(10, 5)) # Output: 5 print(math_operations.multiply(10, 5)) # Output: 50 print(math_operations.divide(10, 5)) # Output: 2.0 print(math_operations.divide(10, 0)) # Output: Cannot divide by zero! if __name__ == "__main__": main()
π Exercise 5: Using Built-in Modules
-
Task: Use the
random
module to generate a list of 5 random integers between 1 and 50.import random random_numbers = [random.randint(1, 50) for _ in range(5)] print(random_numbers) # Output: e.g., [23, 5, 47, 12, 34]
7. π Resources
Enhance your learning with these excellent resources:
- Official Python Documentation
- W3Schools Python Tutorial
- Real Python
- Python for Everybody (Coursera)
- Automate the Boring Stuff with Python
- Codecademy Python Course
- LeetCode Python Problems
8. π‘ Tips and Tricks
π‘ Pro Tip
Virtual Environments: Always use virtual environments to manage your project dependencies. This keeps your projects isolated and prevents version conflicts.
# Create a virtual environment
python3 -m venv my_env
# Activate the virtual environment
source my_env/bin/activate # On Windows: my_env\Scripts\activate
# Install packages
pip install package_name
π οΈ Recommended Tools
- Visual Studio Code: A powerful code editor with Python extensions.
- PyCharm: An IDE specifically designed for Python development.
- Jupyter Notebook: Interactive notebooks for data analysis and visualization.
π Speed Up Your Coding
- Use List Comprehensions: They provide a concise way to create lists.
squares = [x**2 for x in range(10)]
- Leverage Built-in Functions: Python's standard library offers a plethora of useful functions.
numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # Output: 15 print(max(numbers)) # Output: 5
π Debugging Tips
- Use Print Statements: Simple yet effective for tracking variable values.
- Leverage Debuggers: Tools like the built-in debugger in VS Code can help step through your code.
- Handle Exceptions: Gracefully handle errors to prevent your program from crashing.
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")