Day 3: Advanced Python Concepts
Modules and Packages: Modules in Python are simply Python files with the .py extension
that contain Python code. Packages are directories that contain multiple modules.
# Example of importing a module
import math
print(math.sqrt(25)) # Output: 5.0
Error and Exception Handling: Errors in Python can be handled using try-except blocks,
allowing graceful recovery from potential exceptions.
# Example of error handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Introduction to Numpy: NumPy is a powerful library for numerical computing in Python. It
provides support for multidimensional arrays and matrices.
# Example of using NumPy
import numpy as np
arr = np.array([1, 2, 3])
print(arr) # Output: [1 2 3]
1. Array Creation
numpy.array(): Create an array from a list or tuple.
numpy.zeros(): Create an array filled with zeros.
numpy.ones(): Create an array filled with ones.
numpy.arange(): Create an array with a range of values.
numpy.linspace(): Create an array with linearly spaced values.
numpy.random(): Functions to create arrays with random numbers, such as
numpy.random.rand(), numpy.random.randn(), etc.
2. Array Properties
ndarray.shape: Get the shape of an array.
ndarray.ndim: Get the number of dimensions of an array.
ndarray.size: Get the number of elements in an array.
ndarray.dtype: Get the data type of the array elements.
3. Array Manipulation
numpy.reshape(): Change the shape of an array.
numpy.flatten(): Flatten a multi-dimensional array to a one-dimensional array.
numpy.transpose(): Transpose the array (swap axes).
numpy.concatenate(): Concatenate two or more arrays along a specified axis.
numpy.split(): Split an array into multiple sub-arrays.
4. Indexing and Slicing
Basic slicing: array[start:stop:step].
Boolean indexing: array[array > value].
Fancy indexing: array[[index1, index2, ...]].
5. Mathematical Operations
Arithmetic operations: +, -, *, /, etc., performed element-wise.
numpy.sum(), numpy.mean(), numpy.std(): Aggregation functions.
numpy.dot(): Dot product of two arrays.
numpy.matmul(): Matrix multiplication.
numpy.linalg.inv(): Inverse of a matrix.
numpy.linalg.eig(): Eigenvalues and eigenvectors.
6. Statistical Functions
numpy.min(), numpy.max(): Minimum and maximum values.
numpy.median(): Median value.
numpy.percentile(): Percentiles of the array elements.
7. File I/O
numpy.loadtxt(), numpy.genfromtxt(): Load data from text files.
numpy.savetxt(): Save an array to a text file.
numpy.save(), numpy.load(): Save and load arrays in binary format (NumPy .npy
files).
8. Special Functions
numpy.fft: Fast Fourier Transform.
numpy.polynomial: Polynomial functions.
numpy.random: Random number generation and random distributions.
9. Universal Functions (ufuncs)
Functions that operate element-wise on arrays, such as numpy.sin(), numpy.exp(),
numpy.log(), etc.
Day 3: Advanced Python Concepts
Modules and Packages
Modules:
A file containing Python code (functions, classes, variables)
Example:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
import mymodule
print(mymodule.greet("Alice"))
Built-in modules: math, datetime, os, etc.
Packages:
A directory containing multiple Python modules
Must contain an __init__.py file
Example directory structure:
mypackage/
__init__.py
module1.py
module2.py
Importing from a package:
from mypackage import module1
print(module1.some_function())
Error and Exception Handling
Try-Except Block:
Used to handle exceptions
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Finally Block:
Executes code regardless of whether an exception occurred
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This runs no matter what")
Raising Exceptions:
Use raise to trigger an exception
Example:
def check_positive(x):
if x < 0:
raise ValueError("x should be positive")
check_positive(-1)
Introduction to Numpy: Arrays, Array Operations
Numpy:
Fundamental package for numerical computing
Install with pip install numpy
Arrays:
Created using numpy.array()
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3], [4, 5, 6]])
Array Operations:
Element-wise operations: a + 1, a * 2
Matrix operations: np.dot(a, b), a.T (transpose)
Universal functions: np.sqrt(a), np.exp(a)
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # Output: [5 7 9]
print(a * b) # Output: [ 4 10 18]