Lab: The “Config Generator”
Scenario: You need to create a configuration string for a database connection. The database password has special characters, and the directory path is on Windows.
Task: Create the connection string correctly without errors.
# Inputs
db_host = "192.168.1.50"
db_port = 5432
# Note: Raw string used here because of backslashes in path
db_path = r"D:\Data\Systems\db_vol"
# Note: Standard string used, but we must be careful if it had quotes
db_pass = "Secure#Pass123"
# Creating the Connection String using f-string (The best way)
connection_string = f"""
[Database Config]
Host: {db_host}
Port: {db_port}
Path: {db_path}
Password: {db_pass}
Status: Active
"""
print(connection_string)
Output:
[Database Config]
Host: 192.168.1.50
Port: 5432
Path: D:\Data\Systems\db_vol
Password: Secure#Pass123
Status: ActiveLab: The “Smart” Registration Form (Beginner)
Concept: Input handling, cleaning whitespace, and standardizing text case. Scenario: Users often enter data messily (e.g., ” jOhn “, “INDIA “). Your script must clean this up before saving it to a database.
Task:
- Accept a username and country from the user.
- Remove extra spaces from the start/end.
- Format the name to “Title Case” (e.g., John).
- Format the country to “Upper Case” (e.g., INDIA).
- Generate a welcome message using an f-string.
# 1. Take dirty input (simulating user typing)
raw_name = " raHul "
raw_country = " india "
print(f"Raw Input: '{raw_name}' and '{raw_country}'")
# 2. Clean and Format
# strip() removes spaces, title() fixes capitalization
clean_name = raw_name.strip().title()
# strip() removes spaces, upper() capitalizes everything (standard for country codes)
clean_country = raw_country.strip().upper()
# 3. Generate Output
welcome_msg = f"Welcome, {clean_name}! Registration for {clean_country} is complete."
print(welcome_msg)
# Expected Output: Welcome, Rahul! Registration for INDIA is complete.
Lab 2: The Log Analyzer (Intermediate)
Concept: String slicing, finding indices, and parsing unstructured text. Scenario: You have a long server log string. You need to extract the specific Transaction ID hidden inside it to debug an error.
Data: INFO 2026-01-25 [Server-1] TransactionID:TXN-998877 completed successfully.
Task: Locate where the ID starts and ends, extract it, and verify it starts with “TXN”.
log_line = "INFO 2026-01-25 [Server-1] TransactionID:TXN-998877 completed successfully."
# 1. Find the starting position
# We look for the label "TransactionID:"
start_marker = "TransactionID:"
start_index = log_line.find(start_marker)
# 2. Calculate the exact start of the value
# We add the length of the marker so we start reading AFTER the colon
value_start = start_index + len(start_marker)
# 3. Find the ending position
# The ID ends where the next space begins
end_index = log_line.find(" ", value_start)
# 4. Slice the string
txn_id = log_line[value_start:end_index]
print(f"Extracted ID: {txn_id}")
# 5. Validation Check
if txn_id.startswith("TXN"):
print("Valid Transaction format.")
else:
print("Invalid format!")
Lab: The SQL Injection Blocker (DevSecOps Focus)
Concept: String replacement (.replace()) and security sanitization. Scenario: A hacker tries to input a username with a single quote ' to break your database query (SQL Injection). As a DevSecOps engineer, you must neutralize this threat.
Input: admin' OR '1'='1 Task: Detect the dangerous character (') and remove it before processing.
# Dangerous input mimicking a hacker
user_input = "admin' OR '1'='1"
print(f"Malicious Input: {user_input}")
# 1. Detect Threat
# logic: if a single quote exists, it is risky
if "'" in user_input:
print("WARNING: SQL Injection attempt detected!")
# 2. Sanitize (Neutralize the threat)
# We replace the single quote with an empty string (delete it)
safe_input = user_input.replace("'", "")
print(f"Sanitized Input: {safe_input}")
else:
print(f"Input is safe: {user_input}")
# Result: The script processes "admin OR 1=1", which effectively breaks the attack logic.Lab: The Dynamic Kubernetes Config Generator (Architect Level)
Concept: Multi-line strings ("""), formatting, and automation. Scenario: You need to deploy 50 microservices. Writing 50 YAML files manually is impossible. You need a Python script to generate the Kubernetes configuration string dynamically based on the App Name and Port.
Task: Create a template using a multi-line f-string and fill it with variables.
# Configuration Variables
app_name = "payment-service"
image_version = "v2.5.0"
container_port = 8080
env_type = "Production"
# Creating the YAML Manifest
# We use triple quotes (""") to keep the indentation (crucial for YAML)
k8s_manifest = f"""
apiVersion: apps/v1
kind: Deployment
metadata:
name: {app_name}
labels:
env: {env_type}
spec:
replicas: 3
template:
spec:
containers:
- name: {app_name}
image: myrepo/{app_name}:{image_version}
ports:
- containerPort: {container_port}
"""
print("--- Generated Kubernetes Manifest ---")
print(k8s_manifest)
# Note: In a real script, you would write this string to a file like 'deployment.yaml'