QA
General
Sure Pavan, here’s a list of commonly asked general Python questions specifically tailored for DevOps/SRE interviews — designed to be practical, conversational, and focused on real-world usage rather than deep software engineering theory.
🐍 Python – General Q&A for DevOps/SRE Interviews
🔹 1. How do you use Python in your day-to-day DevOps/SRE tasks?
Answer:
I use Python to automate tasks like log rotation, server health checks, API calls, AWS automation using boto3, and writing custom CLI tools or alerting scripts.
🔹 2. What’s the difference between a list and a dictionary in Python?
Answer:
List: Ordered, indexed, stores values
Dict: Unordered (before 3.7), stores key-value pairs Dict is best for configuration or lookup operations.
🔹 3. How do you handle errors in Python scripts?
Answer: Using try-except blocks:
try:
risky_function()
except Exception as e:
print(f"Error: {e}")For automation, I log errors or trigger alerts.
🔹 4. What libraries do you commonly use in your Python scripts?
Answer:
os,subprocess– for shell & file operationsboto3– AWS automationrequests– REST APIsyaml,json– config handlingpsutil– system monitoringargparse– CLI inputs
🔹 5. How do you schedule a Python script?
Answer:
Use cron (
crontab -e) for schedulingFor scripts, I often use
scheduleorAPSchedulerlibraries in long-running jobs
🔹 6. What is argparse used for?
argparse used for?Answer: It’s used to parse command-line arguments for Python scripts. Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--env")
args = parser.parse_args()🔹 7. How do you execute a Linux command from Python?
Answer:
import subprocess
output = subprocess.check_output(["df", "-h"])Used for tasks like disk space checks or reboots.
🔹 8. How do you parse JSON or YAML config files in Python?
Answer:
import json
with open("config.json") as f:
data = json.load(f)For YAML:
import yaml
yaml.safe_load(open("config.yaml"))🔹 9. How do you monitor system metrics like CPU or memory in Python?
Answer:
With psutil:
import psutil
psutil.cpu_percent()
psutil.virtual_memory()🔹 10. How do you debug a Python script?
Answer: I use:
print()statements for quick checkspdbmodule for step-by-step debuggingIDE debuggers (VS Code/PyCharm)
Logs with the
loggingmodule
🔹 11. How do you handle large log files in Python?
Answer: Use file streaming:
with open("log.txt") as f:
for line in f:
process(line)Prevents loading large files entirely into memory.
🔹 12. What is the use of with statement in Python?
with statement in Python?Answer: Used for resource management — automatically closes files/sockets:
with open("file.txt") as f:
data = f.read()🔹 13. How do you check if a file or directory exists?
Answer:
import os
os.path.exists("/etc/passwd")🔹 14. How do you write logs in Python scripts?
Answer:
import logging
logging.basicConfig(filename='app.log', level=logging.INFO)
logging.info("Script started")🔹 15. What’s the difference between == and is in Python?
== and is in Python?Answer:
==checks valueischecks object identity Example:
a = [1]; b = a
a == b → True
a is b → True🔹 16. How do you make your Python script executable on Linux?
Answer:
Add shebang:
#!/usr/bin/env python3at topMake executable:
chmod +x script.pyRun:
./script.py
🔹 17. How do you read environment variables in Python?
Answer:
import os
db_user = os.getenv("DB_USER")🔹 18. How do you create a simple REST API in Python?
Answer: Using Flask:
from flask import Flask
app = Flask(__name__)
@app.route("/health")
def health(): return {"status": "ok"}
app.run()🔹 19. What is the purpose of requirements.txt?
requirements.txt?Answer: It lists all the packages your Python app depends on. Install with:
pip install -r requirements.txt🔹 20. How do you write a basic unit test in Python?
Answer:
import unittest
class TestApp(unittest.TestCase):
def test_add(self):
self.assertEqual(1+1, 2)✅ Bonus: Python Automation Ideas for DevOps
AWS backup via boto3
Automate S3 snapshot uploads
Disk usage alerts
Check psutil.disk_usage()
Service health checker
Ping & alert if unreachable
Log parsing/alerting
Parse /var/log/syslog
Slack alerts for failures
Use requests.post() to webhook
Would you like:
📄 A printable cheat sheet PDF
🧪 Hands-on Python automation projects
🧵 Reel or carousel post content using this
Let me know, Pavan — I can also create topic-wise sets for requests, boto3, yaml, or argparse specifically!
Basic
Here you go, Pavan — a list of theory-based Python questions commonly asked to DevOps/SRE professionals. These questions help interviewers assess your core understanding of Python beyond just scripting — perfect for explaining your thought process confidently.
🧠 Python Theory Q&A for DevOps/SRE Interviews
🔸 1. What is Python, and why is it popular for DevOps/SRE work?
Answer:
Python is a high-level, interpreted language known for its readability and simplicity. It’s widely used in DevOps for automation, configuration management, monitoring, scripting, and integrating with APIs or cloud SDKs (like boto3 for AWS).
🔸 2. What is the difference between a list and a tuple?
Answer:
listis mutable (can change), slower, uses more memorytupleis immutable (cannot change), faster, safer for fixed data Example:
a = [1, 2]; a[0] = 5 # valid
b = (1, 2); b[0] = 5 # error🔸 3. **What are *args and kwargs in Python functions?
Answer:
*args: allows passing variable number of positional arguments**kwargs: allows passing variable number of keyword arguments Used for flexible function design.
def f(*args, **kwargs):
print(args, kwargs)🔸 4. What is the difference between Python 2 and Python 3?
Answer: Python 3 introduced:
print()as a functionBetter Unicode support
Division differences (
/vs//) Python 2 is deprecated as of Jan 2020.
🔸 5. What are Python virtual environments? Why are they important?
Answer:
venv creates isolated environments to manage dependencies per project. Prevents conflicts between system-wide and app-specific Python packages.
🔸 6. What is a Python dictionary, and how is it used?
Answer:
A dictionary (dict) is a key-value store used for structured data.
Example:
data = {"name": "pavan", "role": "devops"}🔸 7. What are decorators in Python?
Answer: Decorators are functions that modify other functions. Useful for logging, authentication, retries, etc.
@my_decorator
def my_function():
pass🔸 8. What is a lambda function in Python?
Answer: Anonymous one-liner function.
add = lambda x, y: x + yUseful in short transformations or with map, filter.
🔸 9. What’s the difference between is and == in Python?
is and == in Python?Answer:
is: compares identity (memory location)==: compares values
a = [1]; b = a; a is b → True
a == b → True🔸 10. What are modules and packages in Python?
Answer:
Module: a
.pyfilePackage: directory with
__init__.py, contains multiple modules They help organize reusable code.
🔸 11. What is exception handling in Python?
Answer: Used to catch and handle runtime errors:
try:
risky_code()
except Exception as e:
print(e)
finally:
cleanup()🔸 12. What is list comprehension in Python?
Answer: A concise way to create lists:
squares = [x*x for x in range(5)]Cleaner and faster than using for loops.
🔸 13. What are Python data types you commonly use in DevOps scripts?
Answer:
str,int,list,dict,bool,tuple,setMost configs usedict, file reading usesstr, API calls usejson(dict).
🔸 14. What is the difference between global and nonlocal?
global and nonlocal?Answer:
global: refers to variables at module levelnonlocal: refers to variables in enclosing function scope
🔸 15. What is the difference between shallow copy and deep copy?
Answer:
Shallow copy copies references
Deep copy copies full object recursively Use
copymodule:
from copy import deepcopy🔸 16. What is the use of __init__.py?
__init__.py?Answer: Marks a directory as a Python package. Also used to initialize or pre-load modules.
🔸 17. How is Python used in monitoring/logging pipelines?
Answer: Used with:
APIs (send alerts to Slack, Discord)
Log parsing (grep-like with regex)
Metric collection with
psutil,prometheus_client
🔸 18. What is the Global Interpreter Lock (GIL)?
Answer: A mechanism in CPython that prevents multiple native threads from executing Python bytecodes in parallel. Limits true multithreading but async/multiprocessing are workarounds.
🔸 19. What are Python’s memory management features?
Answer:
Automatic garbage collection
Reference counting
Cyclic GC for unreachable objects
🔸 20. What are common libraries used in DevOps tasks?
Answer:
REST API
requests
OS interaction
os, shutil
Cloud automation
boto3, azure
Config mgmt
json, yaml
Scheduling
schedule, croniter
Regex parsing
re
Monitoring
psutil, prometheus_client
Would you like:
📘 A full PDF cheat sheet
🧪 Sample theory + hands-on mix questions
🎯 A mock quiz to practice before interviews
📽️ Reels/shorts script ideas for Python interview tips
Let me know how you’d like to use this, Pavan — we can turn this into a full Python for DevOps Interview Series too!
Last updated