Comprehensive Python Programming Guide
Comprehensive Python Programming Guide
Notebook
From Fundamentals to Advanced Industrial Applications
Table of Contents
1. Part 1: Python Fundamentals (Chapters 1-6)
2. Part 2: Object-Oriented Programming & Modules (Chapters 7-8)
3. Part 3: Data Structures & Algorithms (Chapters 9-10)
4. Part 4: Libraries & Advanced Concepts (Chapters 11-14)
5. Part 5: Web Development & APIs (Chapters 15-16)
6. Part 6: Data Science & Machine Learning (Chapters 17-19)
7. Part 7: Industrial Applications & Automation (Chapters 20-23)
8. Part 8: Projects & Real-World Implementation (Chapters 24-27)
On Windows: Download from [Link], run installer, ensure "Add Python to PATH"
On macOS: Use Homebrew (brew install python3)
On Linux: apt-get install python3 (Ubuntu/Debian) or equivalent
Verify Installation:
python --version # Should show Python 3.x.x
python -c "import sys; print([Link])"
Package Manager - pip:
Activate (Windows)
myproject_env\Scripts\activate
Activate (macOS/Linux)
source myproject_env/bin/activate
Install packages
pip install numpy pandas
Deactivate
deactivate
Single-line comment
"""
Multi-line comment (string literal)
Used for module docstrings and
longer explanations
"""
'''
Triple single-quoted comment
Also works for multi-line comments
'''
Type checking
type(name) # <class 'str'>
type(age) # <class 'int'>
isinstance(age, int) # True
Naming Conventions (PEP 8[1]):
Constants - UPPER_SNAKE_CASE
PI = 3.14159
MAX_ITERATIONS = 1000
Arithmetic operations
a = 10
b=3
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.333... (float)
floor_division = a // b # 3 (integer division)
modulo = a % b # 1 (remainder)
exponent = a ** b # 1000 (power)
Compound assignment
x=5
x += 3 # x = 8
x -= 2 # x = 6
x *= 2 # x = 12
x //= 3 # x = 4
Common functions
abs(-10) # 10 (absolute value)
round(3.7) # 4 (nearest integer)
pow(2, 3) # 8 (2^3)
max(5, 2, 8, 1) # 8
min(5, 2, 8, 1) # 1
2.5 String Operations
String creation
text = "Hello, Python!"
multiline = """This is
a multiline
string"""
String methods
[Link]() # 'python'
[Link]() # 'PYTHON'
[Link]("Python", "Programming") # 'Hello, Programming!'
[Link](", ") # ['Hello', 'Python!']
[Link]() # Remove leading/trailing whitespace
[Link]("Hello") # True
[Link]("!") # True
[Link]("Python") # 7 (index where found)
String formatting
name = "Alice"
age = 25
.format() method
message = "My name is {} and I'm {} years old".format(name, age)
% formatting (older, avoid for new code)
message = "My name is %s and I'm %d years old" % (name, age)
if statement
age = 18
if age >= 18:
print("You are an adult")
if-else statement
if age < 18:
status = "minor"
else:
status = "adult"
if-elif-else statement
if age < 13:
category = "child"
elif age < 18:
category = "teenager"
elif age < 65:
category = "adult"
else:
category = "senior"
Nested if statements
if temperature > 30:
if humidity > 70:
print("Hot and humid")
else:
print("Hot and dry")
else:
print("Cool")
Ternary operator (conditional expression)
status = "adult" if age >= 18 else "minor"
result = value_if_true if condition else value_if_false
Boolean Operations:
Logical operators
x=5
if x > 0 and x < 10: # Both conditions must be True
print("x is between 0 and 10")
Comparison operators
x == y # Equal to
x != y # Not equal to
x > y # Greater than
x < y # Less than
x >= y # Greater or equal
x <= y # Less or equal
Using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
String iteration
for char in "Python":
print(char)
Dictionary iteration
person = {"name": "John", "age": 30, "city": "NYC"}
for key, value in [Link]():
print(f"{key}: {value}")
While Loops:
Basic while loop
count = 0
while count < 5:
print(count)
count += 1
Nested Loops:
Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} × {j} = {i*j}")
3.3 Flowchart Example
Chapter 4: Functions
4.1 Defining and Calling Functions
Basic function
def greet():
print("Hello, World!")
greet() # Call the function
Default parameters
def power(base, exponent=2):
return base ** exponent
power(5) # 25 (exponent defaults to 2)
power(5, 3) # 125 (exponent is 3)
Named arguments
def create_user(username, email, age=18):
return f"User: {username}, Email: {email}, Age: {age}"
create_user("john", "john@[Link]")
create_user(username="alice", email="alice@[Link]", age=25)
create_user(age=30, email="bob@[Link]", username="bob")
def increment():
global counter
counter += 1
increment()
print(counter) # 1
Nonlocal keyword - for nested functions
def outer():
value = 10
def inner():
nonlocal value
value = 20
inner()
print(value) # 20
outer()
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
Example:
>>> calculate_area(5)
78.53981633974483
"""
return 3.14159 * radius ** 2
Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]
Accessing elements
numbers[0] # 1 (first element)
numbers[-1] # 5 (last element)
numbers[1:3] # [2, 3] (slice from index 1-2)
numbers[::-1] # [5, 4, 3, 2, 1] (reversed)
List methods
[Link](6) # Add to end
[Link](0, 0) # Insert at position
[Link]([7, 8, 9]) # Add multiple items
removed = [Link]() # Remove and return last item
[Link](3) # Remove by value
[Link]() # Remove all items
count = [Link](2) # Count occurrences
index = [Link](4) # Find index of value
List comprehension (elegant and efficient)
squares = [x ** 2 for x in range(10)]
5.2 Tuples
Tuples are ordered, immutable collections:
Creating tuples
empty_tuple = ()
single_item = (1,) # Note the comma
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14)
x=10, y=20
Tuple methods (limited)
[Link](3) # 1
[Link](2) # 1
5.3 Dictionaries
Dictionaries are unordered, mutable key-value collections:
Creating dictionaries
empty_dict = {}
person = {"name": "Alice", "age": 25, "city": "NYC"}
numbers = {1: "one", 2: "two", 3: "three"}
Accessing values
person["name"] # "Alice"
[Link]("age") # 25
[Link]("country", "USA") # "USA" (default if key missing)
Adding/updating values
person["email"] = "alice@[Link]" # Add new key-value
person["age"] = 26 # Update existing
Removing items
del person["city"] # Remove key
removed_value = [Link]("email") # Remove and return value
[Link]() # Remove all items
Dictionary methods
person = {"name": "Alice", "age": 25}
[Link]() # dict_keys(['name', 'age'])
[Link]() # dict_values(['Alice', 25])
[Link]() # dict_items([('name', 'Alice'), ('age', 25)])
"name" in person # True
Dictionary iteration
for key in person:
print(key, person[key])
Dictionary comprehension
squares = {x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Nested dictionaries
company = {
"name": "TechCorp",
"employees": [
{"name": "Alice", "role": "Engineer"},
{"name": "Bob", "role": "Manager"}
],
"location": {"city": "NYC", "country": "USA"}
}
company["employees"][0]["name"] # "Alice"
5.4 Sets
Sets are unordered, mutable collections of unique items:
Creating sets
empty_set = set() # {} creates empty dict, not set
numbers = {1, 2, 3, 4, 5}
mixed = {1, "hello", 3.14}
Set operations
[Link](6) # Add single item
[Link]({7, 8, 9}) # Add multiple items
[Link](3) # Remove (error if not found)
[Link](3) # Remove (no error if not found)
popped = [Link]() # Remove and return random item
Set comprehension
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
Membership testing
3 in {1, 2, 3} # True
Chapter 6: Working with Files
6.1 Reading Files
Reading CSV
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row) # Each row is a list
Writing CSV
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Name", "Age", "City"])
[Link](["Alice", 25, "NYC"])
[Link](["Bob", 30, "LA"])
Using DictWriter
with open("[Link]", "w", newline="") as file:
fieldnames = ["Name", "Age", "City"]
writer = [Link](file, fieldnames=fieldnames)
[Link]()
[Link]({"Name": "Alice", "Age": 25, "City": "NYC"})
6.4 Working with JSON Files
import json
Reading JSON
with open("[Link]", "r") as file:
data = [Link](file)
print(data)
Writing JSON
data = {
"name": "Alice",
"age": 25,
"city": "NYC",
"hobbies": ["reading", "coding"]
}
with open("[Link]", "w") as file:
[Link](data, file, indent=2)
PART 2: OBJECT-ORIENTED
PROGRAMMING & MODULES
Chapter 7: Object-Oriented Programming (OOP)
7.1 Classes and Objects
# Constructor (initializer)
def __init__(self, name, student_id, gpa):
# Instance variables
[Link] = name
self.student_id = student_id
[Link] = gpa
# Instance method
def display_info(self):
print(f"Name: {[Link]}")
print(f"ID: {self.student_id}")
print(f"GPA: {[Link]}")
# Class method
@classmethod
def from_string(cls, student_string):
"""Create Student from formatted string"""
name, student_id, gpa = student_string.split(",")
return cls(name, student_id, float(gpa))
# Static method
@staticmethod
def is_passing_gpa(gpa):
"""Check if GPA is passing"""
return gpa >= 2.0
Creating objects
student1 = Student("Alice", 12345, 3.8)
student1.display_info()
student2 = Student.from_string("Bob,12346,3.5")
if Student.is_passing_gpa([Link]):
print(f"{[Link]} has passing GPA")
7.2 Inheritance
Parent class
class Employee:
def init(self, name, employee_id, salary):
[Link] = name
self.employee_id = employee_id
[Link] = salary
def display_info(self):
print(f"Name: {[Link]}")
print(f"ID: {self.employee_id}")
print(f"Salary: ${[Link]}")
def calculate_bonus(self):
return [Link] * 0.1 # 10% bonus
def display_info(self):
super().display_info()
print(f"Department: {[Link]}")
def calculate_bonus(self):
return [Link] * 0.15 # 15% bonus for managers
Engineer class
class Engineer(Employee):
def init(self, name, employee_id, salary, specialty):
super().init(name, employee_id, salary)
[Link] = specialty
Usage
manager = Manager("Alice", 1001, 80000, "Engineering")
engineer = Engineer("Bob", 1002, 70000, "Machine Learning")
manager.display_info()
print(f"Bonus: ${manager.calculate_bonus()}")
7.3 Polymorphism
class Cat(Animal):
def speak(self):
return "Meow!"
class Bird(Animal):
def speak(self):
return "Tweet!"
Using polymorphism
animals = [Dog(), Cat(), Bird()]
for animal in animals:
print([Link]())
Output:
Woof!
Meow!
Tweet!
Duck typing - if it quacks like a duck, it's a
duck
class Duck:
def quack(self):
return "Quack!"
def make_sound(animal):
return [Link]() # Works with any object that has speak()
def make_quack(duck):
return [Link]() # Works with any object that has quack()
7.4 Encapsulation
# Getter
@property
def balance(self):
return self._balance
# Setter
@[Link]
def balance(self, amount):
if amount < 0:
raise ValueError("Balance cannot be negative")
self._balance = amount
Concrete implementation
class CSVProcessor(DataProcessor):
def process(self, data):
self.log_processing(f"Processing {len(data)} CSV rows")
return [[Link](",") for row in data]
class JSONProcessor(DataProcessor):
def process(self, data):
import json
self.log_processing("Processing JSON data")
return [Link](data)
Usage
csv_proc = CSVProcessor()
data = ["name,age\nAlice,25\nBob,30"]
if csv_proc.validate(data):
result = csv_proc.process(data)
Chapter 8: Modules and Packages
8.1 Creating and Using Modules
module_example.py
"""
Module for mathematical operations
"""
def add(a, b):
"""Add two numbers"""
return a + b
def multiply(a, b):
"""Multiply two numbers"""
return a * b
class Calculator:
"""Simple calculator class"""
def init(self):
[Link] = 0
my_package/
├── [Link]
├── [Link]
├── [Link]
└── subpackage/
├── [Link]
└── [Link]
my_package/[Link]
"""My package for various utilities"""
my_package/[Link]
def function1():
return "Function 1"
Creating deque
queue = deque([1, 2, 3])
stack = deque()
Deque operations
[Link](4) # Add to right: [1, 2, 3, 4]
[Link](0) # Add to left: [0, 1, 2, 3, 4]
right_val = [Link]() # Remove from right: 4
left_val = [Link]() # Remove from left: 0
while queue:
vertex = [Link]()
if vertex not in visited:
print(vertex)
[Link](vertex)
[Link](graph[vertex])
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'E'],
'D': ['B'],
'E': ['C']
}
bfs_traversal(graph, 'A')
9.2 Heap
import heapq
heap = [1, 3, 7, 5]
smallest = [Link](heap) # 1
print(heap) # [3, 5, 7]
Heapify list
numbers = [5, 3, 7, 1]
[Link](numbers)
print(numbers) # [1, 3, 7, 5]
Top N elements
data = [5, 3, 7, 1, 9, 2, 8]
top_3 = [Link](3, data) # [9, 8, 7]
bottom_3 = [Link](3, data) # [1, 2, 3]
text = "the quick brown fox jumps over the lazy dog"
words = [Link]()
word_counts = Counter(words)
[Link](left[i:])
[Link](right[j:])
return result
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return -1
Using built-in bisect module for binary
search
import bisect
sorted_arr = [1, 3, 4, 6, 8, 9]
index = bisect.bisect_left(sorted_arr, 6) # 3
[Link](sorted_arr, 5) # Insert in sorted position
Two Pointers
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
Sliding Window
def max_subarray_sum(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
return max_sum
Array creation
arr = [Link]([1, 2, 3, 4, 5])
zeros = [Link]((3, 3)) # 3×3 matrix of zeros
ones = [Link]((2, 4)) # 2×4 matrix of ones
range_arr = [Link](0, 10, 2) # [0, 2, 4, 6, 8]
linspace = [Link](0, 1, 5) # [0. , 0.25, 0.5 , 0.75, 1. ]
identity = [Link](3) # 3×3 identity matrix
Array operations
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
c = a + b # [5, 7, 9]
c = a * b # [4, 10, 18]
c = a ** 2 # [1, 4, 9]
c = [Link](a) # [1. , 1.41..., 1.73...]
Matrix operations
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
C = [Link](A, B) # Matrix multiplication
C = A @ B # Alternative syntax
Statistics
data = [Link]([10, 20, 30, 40, 50])
mean = [Link](data) # 30.0
std_dev = [Link](data) # 14.14...
variance = [Link](data) # 200.0
max_val = [Link](data) # 50
sum_val = [Link](data) # 150
Array indexing and slicing
arr = [Link]([[1, 2, 3], [4, 5, 6]])
arr[0, 0] # 1 (first element)
arr[0] # [1, 2, 3] (first row)
arr[:, 0] # [1, 4] (first column)
arr[arr > 3] # [4, 5, 6] (boolean indexing)
Shape manipulation
arr = [Link](12)
reshaped = [Link](3, 4) # Reshape to 3×4
flattened = [Link]() # Back to 1D
import pandas as pd
import numpy as np
DataFrame operations
print(df['Name']) # Single column
print(df[['Name', 'Age']]) # Multiple columns
print([Link][0]) # First row by position
print([Link][0]) # First row by index
print([Link](2)) # First 2 rows
print([Link](1)) # Last row
print([Link]()) # Summary statistics
Filtering
adults = df[df['Age'] >= 30]
nyc_residents = df[df['City'] == 'NYC']
Adding columns
df['Salary'] = [50000, 60000, 75000]
Sorting
sorted_df = df.sort_values('Age', ascending=False)
Scatter plot
x = [Link](50)
y = [Link](50)
colors = [Link](50)
sizes = 100 * [Link](50)
Histogram
data = [Link](100, 15, 10000)
[Link](data, bins=50, edgecolor='black', alpha=0.7)
[Link]('Values')
[Link]('Frequency')
[Link]('Distribution')
[Link]()
Bar plot
categories = ['A', 'B', 'C', 'D']
values = [23, 17, 35, 29]
[Link](categories, values, color=['red', 'blue', 'green', 'orange'])
[Link]('Values')
[Link]('Bar Chart')
[Link]()
Subplots
fig, axes = [Link](2, 2, figsize=(12, 8))
Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Multiple exceptions
try:
value = int("abc")
except ValueError:
print("Invalid integer")
except TypeError:
print("Type error occurred")
class NegativeSalaryError(Exception):
"""Exception for negative salary"""
pass
def set_salary(salary):
if salary < 0:
raise NegativeSalaryError("Salary cannot be negative")
return salary
Handling custom exceptions
try:
validate_age(25)
set_salary(-5000)
except InvalidAgeError as e:
print(f"Age validation failed: {e}")
except NegativeSalaryError as e:
print(f"Salary validation failed: {e}")
14.3 Logging
import logging
Configure logging
[Link](
level=[Link],
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
[Link]('[Link]'),
[Link]()
]
)
logger = [Link](name)
Logging exceptions
try:
result = 10 / 0
except ZeroDivisionError:
[Link]("Division by zero occurred")
PART 5: WEB DEVELOPMENT & APIs
Chapter 15: Web Scraping and APIs
15.1 HTTP Requests
import requests
import json
GET request
response = [Link]('[Link]
status_code = response.status_code # 200
data = [Link]() # Parse JSON
text = [Link] # Raw text
POST request
payload = {'username': 'john', 'email': 'john@[Link]'}
response = [Link]('[Link]
json=payload)
Error handling
try:
response = [Link]('[Link]
timeout=5)
response.raise_for_status() # Raise exception for bad status
except [Link] as e:
print(f"Request failed: {e}")
15.2 Web Scraping with BeautifulSoup
from bs4 import BeautifulSoup
import requests
Fetch webpage
response = [Link]('[Link]
soup = BeautifulSoup([Link], '[Link]')
Find elements
title = [Link]('h1').text
links = soup.find_all('a')
CSS selectors
elements = [Link]('[Link] [Link]')
data = soup.select_one('.class-name').text
Navigate HTML
parent = [Link]
children = [Link]
next_sibling = element.next_sibling
Extract attributes
link = [Link]('a')
href = [Link]('href')
id_attr = link['id']
Multiple methods
@[Link]('/submit', methods=['GET', 'POST'])
def submit_form():
if [Link] == 'POST':
data = request.get_json()
return jsonify({'status': 'success', 'data': data})
return 'GET request'
Template rendering
@[Link]('/profile/<user_id>')
def profile(user_id):
user = {'id': user_id, 'name': 'John Doe', 'age': 30}
return render_template('[Link]', user=user)
API endpoint
@[Link]('/api/products', methods=['GET'])
def get_products():
products = [
{'id': 1, 'name': 'Product 1', 'price': 29.99},
{'id': 2, 'name': 'Product 2', 'price': 39.99},
]
return jsonify(products)
Error handling
@[Link](404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
if name == 'main':
[Link](debug=True, port=5000)
PART 6: DATA SCIENCE & MACHINE
LEARNING
Chapter 17: Introduction to Machine Learning[1]
Machine learning enables systems to learn from data:
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LinearRegression
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, mean_squared_error, r2_score
Sample dataset
X = [Link]([
[1, 2], [2, 3], [3, 4], [4, 5],
[5, 6], [6, 7], [7, 8], [8, 9]
])
y = [Link]([2, 5, 8, 11, 14, 17, 20, 23])
Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = [Link](X_test)
Train model
model = LinearRegression()
[Link](X_train_scaled, y_train)
Predictions
y_pred = [Link](X_test_scaled)
Evaluation
rmse = [Link](mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print(f"RMSE: {rmse:.4f}")
print(f"R² Score: {r2:.4f}")
Coefficients
print(f"Coefficients: {model.coef_}")
print(f"Intercept: {model.intercept_}")
Load dataset
iris = load_iris()
X, y = [Link], [Link]
Train/test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
Classification
clf = RandomForestClassifier(n_estimators=100, random_state=42)
[Link](X_train, y_train)
Predictions
y_pred = [Link](X_test)
Evaluation
accuracy = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)
report = classification_report(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f}")
print(f"Confusion Matrix:\n{cm}")
print(f"Classification Report:\n{report}")
Feature importance
importances = clf.feature_importances_
for name, importance in zip(iris.feature_names, importances):
print(f"{name}: {importance:.4f}")
Clustering
kmeans = KMeans(n_clusters=3, random_state=42)
clusters = kmeans.fit_predict(X)
print(f"Cluster centers shape: {kmeans.cluster_centers_.shape}")
print(f"Inertia: {kmeans.inertia_}")
Train model
history = [Link](
X_train, y_train,
epochs=50,
batch_size=16,
validation_split=0.2,
verbose=1
)
Evaluate
test_loss, test_accuracy = [Link](X_test, y_test)
print(f"Test Accuracy: {test_accuracy:.4f}")
Predictions
predictions = [Link](X_test[:5])
predicted_classes = [Link](predictions, axis=1)
PART 7: INDUSTRIAL APPLICATIONS &
AUTOMATION
Chapter 20: Automation and Task Scheduling
20.1 System Automation
import os
import shutil
from pathlib import Path
File operations
def organize_files(source_dir, dest_dir):
"""Organize files by extension"""
Path(dest_dir).mkdir(exist_ok=True)
[Link](
[Link](source_dir, file),
[Link](ext_dir, file)
)
scheduler = BackgroundScheduler()
Scheduled job
def maintenance_task():
print("Running maintenance task...")
# Perform cleanup, data processing, etc.
Schedule job
scheduler.add_job(
maintenance_task,
trigger=CronTrigger(hour=2, minute=0), # Run at 2 AM daily
id='maintenance_job'
)
Interval-based job
def health_check():
print("Health check running...")
scheduler.add_job(
health_check,
trigger='interval',
minutes=5, # Run every 5 minutes
id='health_check'
)
Start scheduler
[Link]()
try:
# Keep application running
while True:
[Link](1)
except KeyboardInterrupt:
[Link]()
Chapter 21: Working with Databases
21.1 SQLite
import sqlite3
Create/connect to database
conn = [Link]('[Link]')
cursor = [Link]()
Create table
[Link]('''
CREATE TABLE IF NOT EXISTS equipment (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
status TEXT,
temperature REAL,
last_maintenance DATE
)
''')
Insert data
[Link]('''
INSERT INTO equipment (name, status, temperature, last_maintenance)
VALUES (?, ?, ?, ?)
''', ('Pump-001', 'running', 65.5, '2025-01-15'))
Commit changes
[Link]()
Query data
[Link]('SELECT * FROM equipment WHERE temperature > ?', (60,))
results = [Link]()
for row in results:
print(row)
Update data
[Link]('''
UPDATE equipment SET status = ? WHERE id = ?
''', ('maintenance', 1))
Delete data
[Link]('DELETE FROM equipment WHERE status = ?', ('offline',))
[Link]()
[Link]()
Base = declarative_base()
Define model
class Equipment(Base):
tablename = 'equipment'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
status = Column(String)
temperature = Column(Float)
last_maintenance = Column(DateTime)
Query data
results = [Link](Equipment).filter([Link] > 60).all()
for eq in results:
print(f"{[Link]}: {[Link]}°C")
Update
equipment = [Link](Equipment).filter_by(id=1).first()
[Link] = 'maintenance'
[Link]()
Delete
[Link](equipment)
[Link]()
[Link]()
def close(self):
self.serial_conn.close()
def connect(self):
[Link]([Link], [Link], 60)
def start(self):
[Link].loop_start()
def stop(self):
[Link].loop_stop()
[Link]()
def start_monitoring(self):
"""Start continuous monitoring"""
[Link] = True
[Link]()
[Link]()
monitoring_thread = [Link](target=self._monitor_loop)
monitoring_thread.start()
def _monitor_loop(self):
"""Main monitoring loop"""
while [Link]:
value = [Link].read_sensor()
[Link](1)
def stop_monitoring(self):
"""Stop monitoring"""
[Link] = False
[Link]()
[Link]()
Usage
monitor = IndustrialMonitor('/dev/ttyUSB0',
'localhost')
monitor.start_monitoring()
Chapter 23: Predictive Maintenance and ML Pipelines[1]
import numpy as np
from [Link] import RandomForestClassifier
from [Link] import StandardScaler
import joblib
from datetime import datetime, timedelta
class PredictiveMaintenanceSystem:
"""System for predicting equipment failures"""
if model_path:
self.load_model(model_path)
[Link] = RandomForestClassifier(
n_estimators=100,
max_depth=10,
random_state=42
)
[Link](X_scaled, y_train)
return [Link]
return {
'failure_probability': failure_prob,
'will_fail_soon': failure_prob > 0.7,
'confidence': max(probability)
}
Usage example
pm_system = PredictiveMaintenanceSystem()
Simulated training data
X_train = [Link]([
[65, 2.1, 500, 0.95], # temperature, vibration, runtime, efficiency
[72, 3.5, 1200, 0.92],
[68, 2.8, 800, 0.94],
[85, 5.2, 2000, 0.45], # This one is failing
[55, 1.2, 300, 0.98],
])
y_train = [Link]([0, 0, 0, 1, 0]) # 1 = will fail, 0 = normal
Train model
pm_system.train_model(X_train, y_train)
import pandas as pd
import numpy as np
import [Link] as plt
from [Link] import StandardScaler
from [Link] import KMeans
import seaborn as sns
class SalesAnalyzer:
"""Analyze sales data and generate insights"""
def load_and_validate(self):
"""Load and validate data"""
print(f"Dataset shape: {[Link]}")
print(f"Missing values:\n{[Link]().sum()}")
print(f"\nData types:\n{[Link]}")
def clean_data(self):
"""Clean and preprocess data"""
# Handle missing values
[Link]([Link](), inplace=True)
# Remove duplicates
[Link].drop_duplicates(inplace=True)
# Create new features
[Link]['revenue'] = [Link]['quantity'] * [Link]['unit_price']
[Link]['date'] = pd.to_datetime([Link]['date'])
[Link]['month'] = [Link]['date'].[Link]
[Link]['quarter'] = [Link]['date'].[Link]
self.processed_df = [Link]
print("Data cleaning completed")
def exploratory_analysis(self):
"""Perform EDA"""
print("\n=== Exploratory Data Analysis ===")
print(f"\nBasic Statistics:")
print(self.processed_df.describe())
print(f"\nSales by Region:")
print(self.processed_df.groupby('region')['revenue'].sum().sort_values(ascend
print(f"\nTop Products:")
print(self.processed_df.groupby('product')['quantity'].sum().sort_values(ascen
def segment_customers(self):
"""Segment customers using clustering"""
features = self.processed_df[['revenue', 'quantity', 'frequency']].values
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
print(f"\nCustomer Segments:")
print(self.processed_df.groupby('segment')['revenue'].agg(['count', 'sum', 'mea
def visualize_insights(self):
"""Create visualizations"""
fig, axes = [Link](2, 2, figsize=(14, 10))
# Revenue by month
monthly = self.processed_df.groupby('month')['revenue'].sum()
axes[0, 0].plot([Link], [Link], marker='o')
axes[0, 0].set_title('Revenue by Month')
axes[0, 0].set_xlabel('Month')
axes[0, 0].set_ylabel('Revenue')
# Revenue by region
regional = self.processed_df.groupby('region')['revenue'].sum().sort_values(as
axes[0, 1].bar([Link], [Link], color='steelblue')
axes[0, 1].set_title('Revenue by Region')
axes[0, 1].tick_params(axis='x', rotation=45)
# Product performance
products = self.processed_df.groupby('product')['quantity'].sum().sort_values(
axes[1, 0].barh([Link], [Link], color='coral')
axes[1, 0].set_title('Top 10 Products by Quantity')
# Customer segments
segments = self.processed_df.groupby('segment')['revenue'].sum()
axes[1, 1].pie([Link], labels=[f'Segment {i}' for i in range(len(segme
autopct='%1.1f%%')
axes[1, 1].set_title('Revenue Distribution by Segment')
plt.tight_layout()
[Link]('sales_analysis.png', dpi=300)
[Link]()
def generate_report(self):
"""Generate comprehensive report"""
self.load_and_validate()
self.clean_data()
self.exploratory_analysis()
self.segment_customers()
self.visualize_insights()
return {
'total_revenue': self.processed_df['revenue'].sum(),
'total_transactions': len(self.processed_df),
'average_transaction': self.processed_df['revenue'].mean(),
'top_region': self.processed_df.groupby('region')['revenue'].sum().idxmax()
}
Usage
analyzer = SalesAnalyzer('sales_data.csv')
report = analyzer.generate_report()
Chapter 25: Real-Time Monitoring Dashboard
from flask import Flask, render_template, jsonify
from flask_socketio import SocketIO
import threading
import time
from datetime import datetime
import random
app = Flask(name)
socketio = SocketIO(app)
class RealTimeMonitor:
"""Monitor industrial equipment in real-time"""
def __init__(self):
[Link] = {
'temperature': 65,
'pressure': 100,
'vibration': 2.5,
'humidity': 45
}
[Link] = False
def simulate_sensor_data(self):
"""Simulate sensor readings"""
[Link]['temperature'] += [Link](-1, 1)
[Link]['pressure'] += [Link](-2, 2)
[Link]['vibration'] += [Link](-0.5, 0.5)
[Link]['humidity'] += [Link](-2, 2)
# Keep values in reasonable range
[Link]['temperature'] = max(50, min(100, [Link]['temperature']))
[Link]['pressure'] = max(90, min(110, [Link]['pressure']))
return [Link]
def monitor_loop(self):
"""Continuous monitoring loop"""
while [Link]:
data = self.simulate_sensor_data()
[Link]('sensor_update', {
'data': data,
'timestamp': [Link]().isoformat()
}, broadcast=True)
[Link](2)
monitor = RealTimeMonitor()
@[Link]('/')
def index():
return render_template('[Link]')
@[Link]('/api/current-data')
def get_current_data():
return jsonify({
'data': [Link],
'timestamp': [Link]().isoformat()
})
@[Link]('connect')
def handle_connect():
print('Client connected')
[Link] = True
thread = [Link](target=monitor.monitor_loop)
[Link]()
@[Link]('disconnect')
def handle_disconnect():
print('Client disconnected')
[Link] = False
if name == 'main':
[Link](app, debug=True, port=5000)
Chapter 26: Automation Task Executor
import schedule
import time
import json
from datetime import datetime
from pathlib import Path
class TaskExecutor:
"""Execute scheduled automation tasks"""
def __init__(self):
[Link] = {}
[Link] = []
result = task['func']()
log_entry = {
'task': task_name,
'status': 'SUCCESS',
'timestamp': [Link]().isoformat(),
'result': result
}
except Exception as e:
log_entry = {
'task': task_name,
'status': 'FAILED',
'timestamp': [Link]().isoformat(),
'error': str(e)
}
[Link](log_entry)
self.save_logs()
def save_logs(self):
"""Save execution logs"""
with open('task_logs.json', 'w') as f:
[Link]([Link], f, indent=2)
def start(self):
"""Start task scheduler"""
while True:
schedule.run_pending()
[Link](60)
def send_notifications():
"""Send alerts and notifications"""
print("Sending notifications...")
# Notification logic here
return {"status": "notifications_sent"}
Setup executor
executor = TaskExecutor()
executor.register_task('backup_db', backup_database, "02:00")
executor.register_task('reports', generate_reports, "06:00")
executor.register_task('cleanup', cleanup_old_logs, "03:00")
executor.register_task('alerts', send_notifications, "08:00")
Start scheduler
[Link]()
Chapter 27: Best Practices and Deployment
27.1 Code Quality Standards[1]
Args:
employees: List of employee dictionaries
Returns:
Tuple of (total_employees, average_salary)
Raises:
ValueError: If employees list is empty
"""
if not employees:
raise ValueError("Employees list cannot be empty")
total = len(employees)
avg_salary = sum(emp['salary'] for emp in employees) / total
Docstring conventions
class DataProcessor:
"""Process and analyze industrial data.
Attributes:
data: Raw input data
processed_data: Cleaned and processed data
errors: List of processing errors
"""
Args:
raw_data: List of sensor readings
Returns:
Processed data after cleaning and filtering
Raises:
ValueError: If raw_data is empty
"""
pass
@staticmethod
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
class TestCalculator([Link]):
"""Unit tests for Calculator class"""
def setUp(self):
"""Setup for each test"""
[Link] = Calculator()
def test_add(self):
"""Test addition"""
[Link]([Link](2, 3), 5)
[Link]([Link](-1, -1), -2)
def test_divide(self):
"""Test division"""
[Link]([Link](10, 2), 5)
[Link]([Link](7, 2), 3.5)
def test_divide_by_zero(self):
"""Test division by zero"""
with [Link](ValueError):
[Link](10, 0)
if name == 'main':
[Link]()
[Link]
List all dependencies with versions
numpy1.24.3
pandas2.0.2
matplotlib3.7.1
scikit-learn1.2.2
flask2.3.2
tensorflow2.12.0
COPY [Link] .
RUN pip install --no-cache-dir -r [Link]
COPY . .
EXPOSE 5000
CMD ["python", "[Link]"]
"""
Logging configuration
import logging
[Link](
level=[Link],
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
[Link]('[Link]'),
[Link]()
]
)
logger = [Link](name)
Conclusion
This comprehensive notebook has covered Python from fundamentals to advanced
industrial applications[1]. The journey includes:
Part 1 (Chapters 1-6): Foundations
Python basics, syntax, control flow, functions, and file operations
Essential for all Python programming
Next Steps
1. Practice: Build projects combining multiple concepts
2. Specialize: Focus on domains matching your interests (ML, web, automation)
3. Contribute: Participate in open-source projects
4. Stay Updated: Follow Python enhancement proposals (PEPs) and new features
5. Community: Join Python communities and attend conferences
References
[1] Invensis Technologies. (2025, October 27). "6 Python Best Practices For Writing Better
Code." Retrieved from [Link]
[2] Real-World Applications of Python Automation in Different Industries. (2025, August 25).
Retrieved from [Link]
hon-automation-in-different-industries
[3] Python Packaging Authority. (2017, December 31). "Packaging Python Projects."
Retrieved from [Link]
[4] Anuj Tomar. (2025, February 10). "10 Best Practices for Secure Coding in Python."
LinkedIn. Retrieved from [Link]
ython-anuj-tomar-mltfc
[5] Real Python. (2025, November 23). "Python Best Practices." Retrieved from [Link]
[Link]/tutorials/best-practices/
[6] PyOpenSci. (2024). "Python Package Structure for Scientific Python Projects." Retrieved
from [Link]
[Link]
[7] Data Mites. (2025, March 25). "Automate Success: Python Scripting for Real-World Jobs."
Retrieved from [Link]
ld-jobs/