Python Basics for Ops

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Python

Python Basics for Ops

Beginner ⭐ 50 XP ⏱ 20 min #python#scripting

The Python essentials an operations engineer reaches for every day.

📖Theory

Python is the default language for automation, glue code, and tooling because it’s readable and batteries-included. The core data structures you’ll use constantly:

  • list — ordered, mutable ([1, 2, 3])
  • dict — key/value map ({"name": "alex"})
  • tuple — immutable sequence; set — unique items

Add functions, f-strings for formatting, and comprehensions for concise data transforms, and you can express most ops logic cleanly. Always target Python 3.

🌍Real-World Example
servers = [
    {"name": "web1", "cpu": 82},
    {"name": "web2", "cpu": 35},
    {"name": "db1", "cpu": 91},
]

# Comprehension: names of servers over 80% CPU
hot = [s["name"] for s in servers if s["cpu"] > 80]
print(f"High CPU: {', '.join(hot)}")     # High CPU: web1, db1

def average(values):
    return sum(values) / len(values) if values else 0

print(f"Avg CPU: {average([s['cpu'] for s in servers]):.1f}")
✍️Hands-On Exercise
  1. Build a list of dicts and filter it with a comprehension.
  2. Write a function that returns the max value in a list, handling the empty case.
  3. Use an f-string to format a number to two decimal places.
  4. Create a virtual environment and confirm which python points inside it.
🧾Cheat Sheet
ItemSyntax
List / dict[1,2] / {"k": v}
f-stringf"{x:.2f}"
Comprehension[x for x in xs if cond]
Functiondef f(a, b=1): ...
Loopfor x in xs:
Venvpython -m venv .venv
Install deppip install pkg
💬Common Interview Questions
When would you choose Python over a shell script?

When logic grows beyond simple command glue — needing data structures, robust error handling, API calls, or testability. Shell is best for short pipelines of CLI tools.

What is a list comprehension?

A concise way to build a list by transforming/filtering an iterable, e.g. [x*2 for x in nums if x > 0].

Why use a virtual environment?

It isolates a project’s dependencies and Python version from the system and other projects, avoiding version conflicts.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type