Top 20 Scenario-Based Python Interview Programs Every Engineer Should Know
Python interviews are no longer about reversing strings and checking palindromes. Modern interviews focus on solving real-world engineering problems.
Here are 20 scenario-based Python programs commonly asked in interviews for DevOps, Cloud, SRE, Platform Engineering, Data Engineering, and Backend roles.
1. Read a Large Log File Efficiently
Scenario: Process a 10GB application log without loading it into memory.
with open("app.log") as f:
for line in f:
if "ERROR" in line:
print(line.strip())
2. Count Occurrences of IP Addresses in Logs
Scenario: Find the most frequent IPs accessing your application.
from collections import Counter
ips = ["10.0.0.1", "10.0.0.2", "10.0.0.1"]
print(Counter(ips).most_common(5))
3. Remove Duplicate Records
Scenario: Clean duplicate user IDs from a dataset.
users = [101, 102, 103, 101, 104]
unique_users = list(set(users))
print(unique_users)
4. Find Top N Largest Values
Scenario: Identify top CPU-consuming servers.
import heapq
cpu = [20, 45, 12, 80, 60]
print(heapq.nlargest(3, cpu))
5. Parse JSON API Response
Scenario: Read data from a REST API.
import json
data = '{"name":"Sachin","role":"DevOps"}'
result = json.loads(data)
print(result["name"])
6. Check Service Health Endpoint
Scenario: Verify if an application is healthy.
import requests
response = requests.get("https://example.com/health")
print(response.status_code == 200)
7. Retry Failed API Calls
Scenario: Handle temporary network failures.
import time
import requests
for attempt in range(3):
try:
r = requests.get("https://api.example.com")
print(r.status_code)
break
except Exception:
time.sleep(2)
8. Monitor Disk Usage
Scenario: Alert when disk usage exceeds threshold.
import shutil
usage = shutil.disk_usage("/")
print(f"Used: {usage.used // (1024**3)} GB")
9. Read Environment Variables
Scenario: Load application configuration securely.
import os
db_host = os.getenv("DB_HOST")
print(db_host)
10. Find Duplicate Files
Scenario: Detect duplicate backups.
import hashlib
def checksum(file):
with open(file, "rb") as f:
return hashlib.md5(f.read()).hexdigest()
11. Generate Random Password
Scenario: Create temporary credentials.
import secrets
import string
password = ''.join(
secrets.choice(string.ascii_letters + string.digits)
for _ in range(12)
)
print(password)
12. Validate Email Address
Scenario: Verify user input.
import re
email = "user@example.com"
print(bool(re.match(r'^[^@]+@[^@]+\.[^@]+$', email)))
13. Calculate API Response Time
Scenario: Measure service latency.
import time
import requests
start = time.time()
requests.get("https://google.com")
print(time.time() - start)
14. Concurrent API Calls
Scenario: Fetch data from multiple services simultaneously.
from concurrent.futures import ThreadPoolExecutor
import requests
urls = ["https://google.com", "https://github.com"]
with ThreadPoolExecutor() as executor:
results = executor.map(requests.get, urls)
for r in results:
print(r.status_code)
15. Find Most Frequent Error Message
Scenario: Analyze application logs.
from collections import Counter
errors = ["DB Error", "Timeout", "DB Error"]
print(Counter(errors).most_common(1))
16. Convert CSV to Dictionary
Scenario: Load infrastructure inventory.
import csv
with open("servers.csv") as f:
data = list(csv.DictReader(f))
print(data)
17. Implement Rate Limiting
Scenario: Prevent API abuse.
import time
last_call = 0
def allow_request():
global last_call
now = time.time()
if now - last_call > 1:
last_call = now
return True
return False
18. Create a Simple Flask Health Check
Scenario: Kubernetes readiness probe.
from flask import Flask
app = Flask(__name__)
@app.route("/health")
def health():
return {"status": "UP"}
app.run()
19. Roll a Dice API
Scenario: Demonstrate REST endpoint development.
from flask import Flask
import random
app = Flask(__name__)
@app.route("/roll")
def roll():
return {"value": random.randint(1,10)}
app.run()
20. Detect High CPU Servers
Scenario: Trigger alerts for overloaded systems.
servers = {
"web1": 40,
"web2": 95,
"web3": 72
}
for server, cpu in servers.items():
if cpu > 80:
print(f"Alert: {server}")
If you can comfortably solve and explain these 20 scenarios, you will be well prepared for most Python interviews focused on DevOps, Cloud, SRE, Platform Engineering, Automation, and Backend development.
Remember: Interviewers are not testing whether you know Python syntax. They are testing whether you can use Python to solve real business and operational problems.
