🐍 Enroll in Python Course →
🐍 Free Lecture Notes

Python Notes — Basics to DevOps Automation

16 modules. Start with zero programming experience, finish able to write a real automation script. No fluff — every concept tied to a working example.

After module 16 you'll have a working Linux server health-check script ready to deploy with cron.

Needs: No prior programming knowledge. Basic Linux terminal familiarity helps from Module 11 onward.

✓ 100% Free 16 Modules 1 Final Project

Tier 1 — Basics

Modules 01–10 · zero experience required
MODULE 01

Introduction to Python

What Python is, where it runs, and why it's the first language for DevOps engineers.

What is Python?

Python is a high-level, general-purpose programming language known for simple, readable syntax. Used in web dev, data science, automation, AI, and DevOps scripting — often the most beginner-friendly first language.

Your first Python program
# Your very first Python program
print("Hello Python")
# Output: Hello Python

What is Python & Why Learn It

  • Interpreted: code runs line by line, no compile step — you see results instantly.
  • Why popular: English-like syntax means beginners write working programs in their first hour.
  • Where it's used: Instagram's backend, NASA data analysis, AI models, Ansible automation.
  • DevOps connection: boto3 (AWS SDK), Ansible itself, and most CI/CD glue scripts are Python.

MODULE 02

Installing Python & Setup

Exact commands to check, install, and verify your setup on Linux, Windows, and Mac.

Check Python version
# Check if Python is already installed
python3 --version
# Output: Python 3.11.4

Install Steps by OS

  • Linux (Ubuntu/Debian): usually pre-installed; if not, sudo apt install python3
  • Windows: python.org/downloads → tick "Add Python to PATH" (most common mistake: forgetting this).
  • Mac: pre-installed, but get the latest via brew install python3
  • Run a file: save as hello.py, run with python3 hello.py
DevOps use: Most DevOps tools (Ansible, AWS CLI helpers, Terraform wrappers) require Python 3.8+. Always verify the version before installing packages on a server.

MODULE 03

Python Syntax Basics

Indentation defines code blocks — the most unique and important Python rule.

Indentation example
# Comments start with #
if True:
    print("Indented = inside the if block")
print("Not indented = outside the block")

Indentation & Syntax Rules

  • Indentation is mandatory: 4 spaces, never tabs — mixing both causes errors.
  • No semicolons: statements end at the newline.
  • Case-sensitive: Name and name are different variables.
  • Common error: IndentationError: expected an indented block — forgot to indent after :
DevOps use: YAML (used in Ansible, Docker Compose, GitHub Actions) also uses indentation for structure — the same mindset applies directly.

MODULE 04

Variables & Data Types

Named containers for data — Python auto-detects the type (dynamic typing).

Variables and types
name = "Devriston"   # str
age = 25             # int
price = 99.50        # float
is_active = True     # bool
print(name, age, price, is_active)
  • str: text, wrapped in quotes — single or double, same result.
  • int / float: whole numbers vs decimal numbers.
  • bool: only True or False (capitalised).
  • Convert types: int("25"), str(25), float("9.5")
DevOps use: Environment variables from os.environ always return strings — you must convert to int or bool before using them in logic.

MODULE 05

Input and Output

print() shows output. input() waits for user input — always returns a string.

Input, output and f-strings
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old")
  • input() is always a string: wrap with int() before doing math.
  • f-strings: f"Hello {name}" — cleanest way to insert variables into text.
  • Common bug: forgetting the conversion causes TypeError: can't add str and int
DevOps use: Automation scripts use print() for structured log output. f-strings appear in every real script to format status messages with variable data.

MODULE 06

Python Operators

Math, comparisons, and logical combinations — used in nearly every line of real code.

Arithmetic and comparison operators
x = 10
y = 3
print(x + y)   # 13 — addition
print(x % y)   # 1  — remainder
print(x > y)   # True — comparison
  • Arithmetic: + - * / // % **
  • Comparison: == != > < >= <= always return True/False.
  • Logical: and, or, not
  • Common confusion: = assigns, == compares — #1 beginner bug.
DevOps use: Comparisons power all threshold checks — "if disk usage > 85, send alert" is pure operator logic. % (modulo) is used in cron-style scheduling logic.

MODULE 07

Conditional Statements

Let your program make decisions — the foundation of all logic.

if / elif / else
age = 20
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")
  • if: runs only if condition is True, always ends with :
  • elif: checked only if previous was False — chain as many as needed.
  • else: fallback — runs if nothing above matched.
DevOps use: "if server is down, restart it; elif it's degraded, alert; else log OK" — this exact pattern powers self-healing scripts and monitoring tools.

MODULE 08

Loops in Python

for = known repeats. while = repeats until condition becomes False.

for loop with range
for i in range(5):
    print("Count:", i)
# Prints Count: 0 through Count: 4
  • range(5): generates 0–4 — stops BEFORE 5, a very common beginner trap.
  • break: exits the loop completely. continue: skips to next repeat.
  • Infinite loop warning: always make sure the while condition changes inside the loop.
DevOps use: Loops iterate over server lists, log lines, or S3 bucket objects — "for each server in fleet, run health check" is pure Python loop logic.

MODULE 09

Functions in Python

Write once, call anywhere — the foundation of organized, maintainable scripts.

Defining and calling a function
def greet(name):
    print(f"Hello, {name}!")

greet("Kamran")
# Output: Hello, Kamran!
  • def: defines a function — it only runs when called by name.
  • return: sends a value back; without it a function returns None
  • Default parameters: def greet(name="Guest") lets you call with no argument.
DevOps use: Real scripts wrap each check in a function — get_disk_usage(), check_memory(), send_alert(). Exactly what the final project builds.

MODULE 10

Python Collections

Store multiple values — list, tuple, dictionary, and set, each with different rules.

Lists and dictionaries
fruits = ["apple", "banana", "mango"]
print(fruits[0])   # apple
fruits.append("grape")

server = {"host": "web-01", "port": 80, "active": True}
print(server["host"])  # web-01
  • List [ ]: ordered, changeable — most commonly used collection.
  • Tuple ( ): ordered, unchangeable — fixed data like coordinates.
  • Dict {key: value}: instant lookup by key — the foundation of JSON data.
  • Set { }: unordered, auto-removes duplicates — useful for deduplication.
DevOps use: Dictionaries map server configs and API responses (JSON becomes a dict). Lists hold server IPs or service names to iterate over.

Tier 2 — Python for DevOps & Linux

Modules 11–16 · bridges basics into real automation
MODULE 11

Error Handling — try / except

Scripts that crash on bad input are useless in production. Handle failures gracefully.

try / except / finally
try:
    value = int(input("Enter a number: "))
    print(100 / value)
except ZeroDivisionError:
    print("Can't divide by zero")
except ValueError:
    print("That wasn't a number")
finally:
    print("Done checking input")
  • try: code that might fail goes here.
  • except: catches a specific error type — be specific, don't use a bare except:
  • finally: always runs — close files, release locks, log "attempt finished".
  • Real use case: a server-check script shouldn't crash because one host is unreachable.

MODULE 12

File Handling & Paths

Reading configs, writing logs, parsing output — every automation script touches the filesystem.

Writing and reading files safely
# Writing and reading a file
with open("status.log", "a") as f:
    f.write("Service checked: OK\n")

with open("status.log", "r") as f:
    for line in f:
        print(line.strip())
  • with open(...) as f: auto-closes the file even if an error happens — always prefer this.
  • Modes: "r" read, "w" overwrite, "a" append.
  • pathlib: modern way to handle paths — from pathlib import Path works across Linux/Windows.

MODULE 13

Modules, pip & Virtual Environments

pip installs external libraries. venv keeps each project's dependencies isolated.

Create venv and install packages
# Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install and freeze dependencies
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt
  • venv: a private copy of Python + packages per project — no version conflicts between projects.
  • requirements.txt: lets anyone (or any CI pipeline) recreate your exact environment.
  • import: use import os for built-ins — no install needed for the standard library.
💡

Best practice: Always create a venv before starting a project. Commit requirements.txt but add venv/ to your .gitignore.


MODULE 14

Working with JSON & APIs

AWS, GitHub, and monitoring tools speak JSON. Here's how Python talks to them.

Calling an API and reading a local JSON config
import requests, json

response = requests.get("https://api.github.com/users/octocat")
data = response.json()
print(data["login"], data["public_repos"])

# Reading a local JSON config (works offline)
with open("config.json") as f:
    config = json.load(f)
print(config["server_name"])
  • requests: the standard library for HTTP APIs — install with pip install requests
  • .json(): converts an API response straight into a Python dictionary.
  • json.load() / json.dump(): read and write JSON files for configs or saved state.
⚠️

Network note: The GitHub example requires internet access. Behind a proxy or restricted network? Use the json.load() example with a local config file as your primary pattern.


MODULE 15

os & subprocess — Automating Linux

Reading env vars, listing files, running real shell commands — Python becomes a DevOps tool.

os.environ and subprocess.run
import os, subprocess

# Read an env var — never hardcode secrets in scripts
api_key = os.environ.get("API_KEY", "not set")

# Run a shell command and capture output
result = subprocess.run(
    ["df", "-h", "/"],
    capture_output=True,
    text=True,
    check=True    # raises CalledProcessError if command fails
)
print(result.stdout)
print("Exit code:", result.returncode)  # 0 = success
  • os.environ: read env vars and secrets — never hardcode API keys in the script.
  • os.listdir() / os.path: walk directories, check if files or paths exist.
  • subprocess.run(): the safe modern way to call shell commands — captures exit codes, stdout, stderr.
  • check=True: raises CalledProcessError if the command fails — always use in production scripts so errors are never silently ignored.
  • sys.argv: read command-line arguments so your script can be reused with different inputs.

MODULE 16 — FINAL PROJECT

Server Health-Check Script

Put it all together — a real, deployable DevOps tool that checks disk, logs, and alerts.

What This Script Does

Checks disk space using subprocess, logs every result to a file in your home directory, and prints an alert if usage crosses 85%. A complete, runnable script you can schedule with cron immediately after finishing this module.

health_check.py — complete script
#!/usr/bin/env python3
import subprocess, datetime
from pathlib import Path

# Log to home dir — no sudo needed
LOG_FILE = Path.home() / "health_check.log"

def get_disk_usage():
    result = subprocess.run(
        ["df", "-h", "/"],
        capture_output=True, text=True, check=True
    )
    return result.stdout.splitlines()[1]

def log_status(line):
    with open(LOG_FILE, "a") as f:
        f.write(f"{datetime.datetime.now()} — {line}\n")

try:
    status = get_disk_usage()
    log_status(status)
    usage_percent = int(status.split()[4].replace("%", ""))
    if usage_percent > 85:
        print(f"⚠️  ALERT: Disk usage at {usage_percent}%")
    else:
        print(f"✅ Disk OK: {usage_percent}% used")
except subprocess.CalledProcessError as e:
    log_status(f"COMMAND ERROR: {e}")
    print("Could not run df — check your system.")
except PermissionError:
    print(f"Cannot write log to {LOG_FILE} — check permissions.")
except Exception as e:
    log_status(f"ERROR: {e}")
    print("Health check failed — see log")

What each part does

  • pathlib.Path.home(): log file goes to your home directory — no sudo required.
  • check=True on subprocess: if df fails, you get a clear error not a silent crash.
  • Specific except blocks: CalledProcessError and PermissionError caught separately for clearer debugging.
  • Schedule it: add to crontab with crontab -e*/5 * * * * python3 ~/health_check.py

🏆 Extend This Project

Schedule it with cron, send the alert to Slack via requests, add memory and CPU checks using psutil, or wire it into the monitoring stack from the DevOps Bootcamp for a real always-on health check.

🐍

Want the hands-on version?

The live DevOps Bootcamp and AI course both build directly on these Python fundamentals — same instructor who wrote these notes, with real projects and live sessions.

Batch info & fee details on request