WhatsApp

Quick Reference

DevOps Notes

40 practical concept cards — searchable, filterable, and shareable with direct links. Each card has a code example and expandable deep-dive. Use these for LinkedIn posts, interview prep, or daily reference.

40Note Cards
8Categories
🔗Deep Links
🎯
New here? Start with these 5 cards, in order
If you've never written code or used Linux before, read these first — each builds on the last.
🔵
New — Beginner Guide
C Programming — Learn from Scratch
Hello World → Variables → Loops → Functions → Arrays → 10 Important Programs with output
🐧Linux5 notes
#01
LinuxServer

Linux vs Windows Server

Linux dominates production because it's open, auditable, lightweight, and fully scriptable. Windows Server costs licensing fees and hides complexity behind GUIs that can't be automated at scale.

# Check OS and kernel uname -a cat /etc/os-release # Linux process list — clean, scriptable ps aux | grep nginx
  • Cost: Linux is free. Windows Server requires CALs + OS licensing.
  • Automation: Linux is shell-native. Everything is a file or a process.
  • Performance: Linux runs faster on the same hardware with lower memory overhead.
  • DevOps fit: Docker, Ansible, Terraform are all Linux-first tools.
  • Security: Linux has fewer vulnerabilities and a much smaller attack surface.
#02
LinuxFoundation

Why Linux Matters in DevOps

Every cloud VM, Docker container, CI runner, and Kubernetes node runs Linux. Linux fluency is the baseline that unlocks the entire DevOps stack. No shortcuts — this is the foundation.

systemctl status nginx journalctl -u nginx --since "1 hour ago" ss -tlnp | grep :80 chmod 640 /etc/nginx/nginx.conf
  • chmod/chown: Control who can read, write, and execute files.
  • systemctl: Start, stop, enable, and inspect services.
  • journalctl: Read structured system logs — your first debugging tool.
  • ss / netstat: See what ports are open and what's listening.
  • cron: Schedule tasks without any orchestration tool.
#03
LinuxAutomation

Automating DevOps Workstations

A fully automated workstation setup means rebuilding your entire dev environment in under 10 minutes. Script once, version-control it, run it anywhere. Never manually install tools again.

#!/bin/bash TOOLS=("git" "docker.io" "ansible" "terraform") for pkg in "${TOOLS[@]}"; do apt-get install -y $pkg && echo "✓ $pkg" done
  • Store dotfiles in Git: .bashrc, .vimrc, .gitconfig — all version-controlled.
  • Use roles: Separate roles for tools, terminal config, SSH setup.
  • Vault for secrets: SSH keys, tokens — encrypted in the repo.
  • Result: New machine fully configured in under 10 minutes.
#04
LinuxHomelab

Building Labs on Old Hardware

You don't need expensive servers. An old laptop or refurbished Dell with 8–16GB RAM runs a full DevOps lab — Linux, Docker, Ansible, and a monitoring stack simultaneously.

free -h # RAM available nproc # CPU cores df -h / # Disk space # 8GB RAM = full DevOps lab possible
  • OS: Ubuntu Server 22.04 LTS — stable, well-documented, free.
  • Virtualization: KVM + libvirt for running multiple VMs on one machine.
  • Containers: Docker Compose for multi-service lab environments.
  • RAM target: 8GB minimum. 16GB for a comfortable multi-VM setup.
  • Networking: Use static IPs for consistent lab addressing.
#05
LinuxHomelab

DevOps Homelab Architecture

A well-designed homelab mirrors production: a control node runs Ansible, target VMs simulate servers, Docker runs services, monitoring watches everything. Same tools, smaller scale.

control-node 192.168.1.10 ├── Ansible + Terraform server-01 192.168.1.11 └── Docker + Compose apps monitor-01 192.168.1.12 └── Prometheus + Grafana
  • Safe failure: Break things without consequences. Learn from real errors.
  • GitHub portfolio: Every lab becomes a documented repo employers can see.
  • Cost: AWS charges by the hour. Your homelab charges once (electricity).
  • Speed: No cloud latency. Instant feedback loops for Ansible and Docker.
🐳Docker5 notes
#06
DockerBasics

What is Docker?

Docker packages your application and all its dependencies into a container — a lightweight, portable unit that runs identically on any machine. No more "works on my laptop".

docker run -d -p 80:80 --name web nginx docker ps docker logs web --follow docker exec -it web bash
  • Image: Read-only template built from a Dockerfile. Stored in a registry.
  • Container: A running instance of an image. Ephemeral by default.
  • Registry: Docker Hub, AWS ECR, GHCR — where images are stored.
  • Volume: Persistent storage that survives container restarts.
  • Network: How containers talk to each other and the outside world.
#07
DockerVMs

Docker vs Virtual Machines

VMs virtualise hardware — each gets its own OS kernel eating GBs of RAM. Docker containers share the host kernel and start in milliseconds. For microservices, Docker wins on density and speed.

VM: App → Guest OS → Hypervisor → Host OS Con: App → Docker Engine → Host OS Startup: VM=60s Container=<1s RAM: VM=2GB Container=50MB
  • Use VMs when: You need full OS isolation, different kernels, or legacy apps requiring a specific OS.
  • Use Containers when: Running microservices, needing fast scaling, or wanting consistent dev/prod environments.
  • Use both: In Kubernetes — VMs (nodes) run container workloads.
#08
DockerStorage

Docker Volumes

Containers are ephemeral — kill one and its filesystem is gone. Volumes are persistent storage managed by Docker, surviving container restarts, removals, and recreations.

version: '3.9' services: postgres: image: postgres:15 volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata: # named — Docker managed
  • Named volumes: Docker manages the path. Best for databases.
  • Bind mounts: Map a host path directly. Good for dev (live reload). Risky in prod.
  • tmpfs: In-memory only. Fast, non-persistent. Good for secrets or temp data.
#09
DockerNetworking

Docker Networking

Containers need to communicate — with each other, the host, and the internet. Docker provides network drivers for each use case: bridge, host, overlay, and none.

docker network create app-net docker run -d --network app-net --name api myapi docker run -d --network app-net --name db postgres # api resolves db by name: db:5432 docker network inspect app-net
  • bridge (default): Isolated network on the host. Containers resolve each other by name.
  • host: Container shares host's network stack. Fastest performance, no isolation.
  • overlay: Multi-host networking for Docker Swarm.
  • none: No networking. Fully isolated container for security-critical workloads.
#10
DockerBest Practices

Docker Mistakes Beginners Make

Most Docker production problems come from the same repeated mistakes: running as root, using :latest tags, ignoring .dockerignore, storing state in containers, and fat images.

# ❌ Bad FROM ubuntu:latest COPY . . # ✅ Good FROM python:3.11-slim COPY requirements.txt . RUN pip install -r requirements.txt USER appuser
  • :latest tags: Unpredictable builds. Always pin image versions.
  • Running as root: Major security risk. Add a non-root USER in your Dockerfile.
  • No .dockerignore: Copies node_modules, .git, secrets into the image.
  • Fat images: Use slim/alpine base images. Multi-stage builds for compiled apps.
  • State in containers: Use volumes for databases and persistent data.
☁️Cloud / AWS5 notes
#11
AWSCompute

What is AWS EC2?

EC2 (Elastic Compute Cloud) is AWS's virtual server service. Pick the CPU, RAM, and OS — AWS runs it. Pay per second. Scale from one instance to thousands in minutes.

aws ec2 run-instances \ --image-id ami-0c55b159cbfafe1f0 \ --instance-type t3.micro \ --key-name my-key \ --security-group-ids sg-12345 ssh -i my-key.pem ubuntu@PUBLIC_IP
  • AMI: Amazon Machine Image — the OS template. Choose Ubuntu, RHEL, Amazon Linux.
  • Instance types: t3.micro (cheap, burstable), m5.large (balanced), c5 (CPU).
  • Elastic IP: Static public IP that persists across instance restarts.
  • Security Groups: Stateful firewall. Define inbound/outbound rules per instance.
  • User Data: Bootstrap script that runs on first launch — install packages, configure services.
#12
AWSNetworking

What is a VPC?

A Virtual Private Cloud is your own isolated network inside AWS. You define IP ranges, subnets, routing tables, and internet access. Think of it as your private data centre in the cloud.

VPC: 10.0.0.0/16 ├── Public: 10.0.1.0/24 ← web+NAT │ ├── EC2 (web server) │ └── NAT Gateway └── Private: 10.0.2.0/24 ← app+db ├── EC2 (app server) └── RDS (database)
  • Subnet: Public subnets have routes to the internet. Private do not.
  • Internet Gateway (IGW): The door between your VPC and the internet.
  • NAT Gateway: Lets private instances reach the internet without being reachable from it.
  • Route Table: Rules for where traffic goes. Associate with subnets.
  • NACL vs Security Group: NACLs are stateless subnet-level rules; SGs are stateful instance-level.
#13
AWSLoad Balancer

Load Balancer Explained

A load balancer distributes incoming traffic across multiple servers so no single instance gets overwhelmed. AWS ALB (Application Load Balancer) works at Layer 7 — routing by URL path, headers, and hostnames.

Client → ALB (port 443) ├── /api/* → Target Group A ├── /app/* → Target Group B └── /* → Target Group C Health Check: GET /health → 200 OK
  • ALB (Application): Layer 7. HTTP/HTTPS. Path and host-based routing. Best for web apps.
  • NLB (Network): Layer 4. TCP/UDP. Ultra-low latency. Best for high-throughput workloads.
  • CLB (Classic): Legacy. Don't use for new projects.
#14
CloudNginx

Reverse Proxy vs Load Balancer

Both sit in front of your servers — but serve different roles. A reverse proxy handles SSL termination, caching, and routing. A load balancer distributes traffic across backend instances.

# nginx as reverse proxy server { listen 443 ssl; server_name api.devriston.com.pk; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; } }
  • Reverse Proxy: Terminates client connections. Handles SSL, caching, compression, auth.
  • Load Balancer: Distributes connections across multiple backend targets.
  • AWS combo: ALB (LB) → EC2s running Nginx (reverse proxy) → application.
#15
AWSArchitecture

High Availability Basics

HA means your system keeps running even when individual components fail. The core principle: eliminate single points of failure. Deploy across multiple AZs. Use health checks and auto-recovery.

HA Architecture — 2 AZ ALB / \ AZ-1 AZ-2 EC2 EC2 RDS ←→ RDS (primary) (standby) Failover: automatic. RTO: ~60s
  • Multi-AZ: Deploy app servers in at least 2 Availability Zones behind a load balancer.
  • RDS Multi-AZ: AWS automatically maintains a standby replica. Failover in ~60 seconds.
  • Auto Scaling Groups: Replace failed instances automatically based on health checks.
  • Stateless apps: Store session data in Redis/ElastiCache, not in-memory.
⚙️Terraform / IaC4 notes
#16
TerraformIaC

Infrastructure as Code

IaC means your servers, networks, and cloud resources are defined in code files — not manually configured. Reproducible, reviewable in Git, and deployable in minutes — not days.

resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" tags = { Name = "devriston-web" ManagedBy = "terraform" } }
  • Reproducibility: Run the same code in dev, staging, and prod — identical infrastructure every time.
  • Version control: Infrastructure changes go through Git PRs, code review, and audit history.
  • Disaster recovery: Rebuild your entire environment from code in minutes, not days.
  • Drift detection: Terraform detects when real infrastructure diverges from declared state.
#17
TerraformMulti-Cloud

Why Terraform Matters

Terraform is cloud-agnostic. Write infrastructure for AWS today, replicate on GCP or Azure tomorrow with minimal changes. 3000+ providers cover everything from DNS to Kubernetes to GitHub.

terraform init # download providers + modules terraform plan # show what will change terraform apply # execute the changes + aws_instance.web will be created Plan: 2 to add, 0 to change, 0 to destroy.
  • Terraform: HCL language. Multi-cloud. 3000+ providers. The industry standard.
  • CloudFormation: AWS-only. YAML/JSON. Good if you're 100% AWS forever.
  • Pulumi: Write IaC in Python/TypeScript/Go. Great for developers who dislike HCL.
#18
TerraformState

Terraform State

Terraform tracks what it has built in a state file. This is how it knows what exists, what changed, and what to destroy. Never commit state to Git — use remote backends like S3 with DynamoDB locking.

terraform { backend "s3" { bucket = "devriston-tf-state" key = "prod/terraform.tfstate" region = "us-east-1" dynamodb_table = "tf-lock" encrypt = true } }
  • Remote backend: Store state in S3. Never local files in a team environment.
  • State locking: Use DynamoDB to prevent simultaneous terraform apply runs.
  • Encryption: State files contain secrets. Always encrypt at rest and in transit.
  • Never edit manually: Direct state edits corrupt tracking. Use CLI commands instead.
#19
AnsibleAutomation

What is Ansible?

Ansible automates server configuration over SSH — no agent required. Write a playbook in YAML, run it against 1 or 1000 servers, get the same result every time. Idempotent by design.

- name: Install and start Nginx hosts: webservers become: true tasks: - apt: name=nginx state=present - service: name=nginx state=started enabled=yes
  • Terraform: Provisions infrastructure (creates servers, networks, databases). Declarative.
  • Ansible: Configures what's inside servers (installs software, manages users). Procedural YAML.
  • Together: Terraform builds the VM, Ansible configures it. Perfect combination.
  • Ansible strength: No agent. Works with any SSH-accessible machine.
🔄CI/CD4 notes
#20
CI/CDPipelines

CI/CD Pipeline Basics

CI automatically builds and tests code on every commit. CD ships passing builds to staging or production. Together: faster, safer shipping — zero manual deployment steps.

name: CI/CD Pipeline on: push: branches: [main] jobs: build-test-deploy: runs-on: ubuntu-latest steps: - docker build → test → push → deploy
  • Source: Git push triggers the pipeline.
  • Build: Compile code, build Docker image, resolve dependencies.
  • Test: Unit tests, integration tests, security scans, linting.
  • Staging deploy: Deploy to pre-production for final verification.
  • Production deploy: Blue/green, canary, or rolling deployment.
#21
CI/CDGitHub Actions

GitHub Actions vs Jenkins

Jenkins is powerful, self-hosted CI — but requires maintenance and plugins. GitHub Actions is managed, YAML-driven, and integrates natively with your repo. For most teams, Actions wins.

Feature GH Actions Jenkins Setup time Minutes Hours/Days Infrastructure Managed Self-hosted Config YAML Groovy DSL Cost Free tier Server cost Marketplace 10,000+ 1,800 plugins
  • GitHub Actions: Code is on GitHub, want zero infra overhead, don't need deep customisation.
  • Jenkins: Complex multi-team pipelines, self-hosted runners for compliance, existing investment.
#22
DockerReliability

Self-Healing Infrastructure

Self-healing means your infrastructure automatically detects and recovers from failures without human intervention. Docker health checks, restart policies, and AWS Auto Scaling are the building blocks.

healthcheck: test: ["CMD","curl","-f", "http://localhost:3000/health"] interval: 30s timeout: 10s retries: 3 restart: unless-stopped
  • Process level: systemd restarts services; Docker restart policies restart containers.
  • Container level: Health checks detect failed containers; Compose replaces them.
  • Instance level: AWS Auto Scaling replaces unhealthy EC2s; ALB stops routing to them.
#23
GitCI/CD

Git Branching Strategy

A branching strategy defines how teams collaborate in Git. GitFlow uses long-lived branches. Trunk-based development uses short-lived feature branches merged to main frequently. For CI/CD, trunk-based wins.

git checkout -b feature/add-monitoring # ... make changes ... git add . && git commit -m "feat: prometheus" git push origin feature/add-monitoring # PR → review → merge → CI/CD triggers
  • Trunk-based: All developers commit to main (or short branches). CI runs on every commit. Fast, clean.
  • GitFlow: main + develop + feature + release + hotfix. Heavyweight but structured.
  • GitHub Flow: main + feature branches + PRs. Simple. Good for small teams.
📊Monitoring3 notes
#24
MonitoringArchitecture

Monitoring Stack Architecture

A production monitoring stack has three jobs: collect metrics (Prometheus), visualise them (Grafana), and alert on anomalies (AlertManager). Each component is purpose-built, composable, and open-source.

Targets (EC2, Docker, Apps) ↓ expose /metrics endpoint Prometheus ← scrapes every 15s ├──→ Grafana (dashboards) └──→ AlertManager (alerts) ↓ Slack / Email / PagerDuty
  • Node Exporter: Linux system metrics — CPU, RAM, disk, network. Run on every server.
  • cAdvisor: Container metrics — per-container CPU, memory from Docker.
  • Blackbox Exporter: HTTP/TCP probing — check if endpoints respond correctly.
  • Postgres Exporter: Database metrics — queries, connections, cache hit rates.
#25
PrometheusPromQL

Prometheus + Grafana Workflow

Prometheus stores time-series metrics and lets you query them with PromQL. Grafana connects to Prometheus as a data source and renders the queries as actionable dashboards.

# CPU usage % across all cores 100 - (avg by(instance)(rate( node_cpu_seconds_total{mode="idle"}[5m] )) * 100) # RAM used % (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100
  • Grafana provisioning: Use YAML to auto-load datasources and dashboards — no manual clicking.
  • AlertManager: Define alert rules in Prometheus, route to AlertManager, configure Slack/email receivers.
  • Dashboard import: Grafana dashboard #1860 = Node Exporter Full. Import by ID.
#26
ProductionLessons

Lessons From Production-Style Labs

Real production experience teaches things no tutorial can. These are hard-won lessons from running actual services, debugging systems at 2am, and learning what monitoring should have caught earlier.

# First checks when something breaks df -h # disk space free -h # memory journalctl -xe --since "10m" # logs ss -tlnp # open ports
  • Monitoring before deployment: If you can't observe it, you can't debug it. Set up metrics before launch.
  • Idempotency matters: Scripts that break if run twice cause more problems than they solve.
  • Document the fix: Post-mortems that only describe what broke are useless. Capture root cause and remediation.
  • Smallest change wins: Change one thing at a time when debugging.
🚀DevOps Career & Mindset4 notes
#27
DevOpsRoadmap

DevOps Roadmap 2026

The fundamentals haven't changed — Linux, networking, Git, CI/CD. What's shifted is the expectation around security (DevSecOps), observability, and platform engineering replacing pure ops roles.

Phase 1: Linux + bash + networking + Git Phase 2: Docker + AWS + Terraform Phase 3: Ansible + GitHub Actions Phase 4: Prometheus + Grafana + Loki Phase 5: Kubernetes + Helm + ArgoCD
  • Platform Engineering: Building internal developer platforms using Backstage, Port, Crossplane.
  • GitOps: ArgoCD and Flux becoming the standard for Kubernetes deployment automation.
  • DevSecOps: Security shifting left — SAST/DAST in pipelines, container scanning (Trivy).
  • FinOps: Cloud cost optimisation is now a required skill, not optional.
#28
DevOpsLearning

How to Learn DevOps Effectively

Most people learn DevOps wrong — watching tutorials and feeling productive but unable to do anything without the video paused. The only path: build real things, break them, fix them, document on GitHub.

Effective Learning Loop 1. Pick one concept (Docker networking) 2. Read the docs (not a tutorial) 3. Build a lab (hands-on) 4. Break something (intentionally) 5. Fix it (debug the error) 6. Document on GitHub (portfolio + learning)
  • Official docs first: Docker docs, Terraform registry, AWS docs. Written by the people who built the tools.
  • Read real codebases: Real Ansible roles, Terraform modules on GitHub teach more than any course.
  • Avoid tutorial hell: If you've watched 5 videos and written 0 code, you're consuming — not learning.
  • Time-box theory: 20% reading, 80% building. Most DevOps concepts click in 2 hours of hands-on work.
#29
DevOpsCareer

Most Important DevOps Skills

The DevOps job market is flooded with tool names but short on engineers who understand systems. The skills that get you hired — and keep you employed — go deeper than any single tool.

Tier 1 — Non-negotiable Linux fundamentals + bash scripting Networking (TCP/IP, DNS, HTTP, TLS) Git + version control workflows Tier 2 — Core DevOps Docker + CI/CD + Cloud + IaC Tier 3 — Differentiators Observability + DevSecOps
  • Go deep before wide: Master Linux before jumping to Kubernetes. Foundation skills compound.
  • Build, don't watch: A working homelab beats 50 YouTube tutorials.
  • Document everything: A well-documented GitHub repo is a portfolio that speaks for you.
  • Read error messages: The ability to interpret logs and stack traces is the most underrated DevOps skill.
#30
DevOpsAutomation

Infrastructure Automation Workflow

A complete infrastructure automation workflow: Terraform provisions resources, Ansible configures them, GitHub Actions orchestrates both, and Prometheus watches the result. Each tool has one job.

Git push → GitHub Actions ├── terraform plan (review) ├── terraform apply (provision) ├── ansible-playbook (configure) └── smoke tests (verify) ↓ Production ↓ Prometheus → Grafana (observe)
  • Plan before apply: Always run terraform plan in CI and require approval before prod apply.
  • Separate provision and config: Terraform provisions the VM; Ansible configures it.
  • Smoke tests post-deploy: Run a health check before marking a deployment as successful.
  • Rollback plan: Know before you deploy how to revert. Terraform can destroy and recreate.
🐍Python Programming10 notes
#31
Python

Introduction to Python

Python is a high-level, general-purpose programming language known for simple, readable syntax. It's used in web development, data science, automation, AI, and DevOps scripting — often called the most beginner-friendly language to learn first.

# Your very first Python program print("Hello Python") # Output: Hello Python
  • What it is: Python is an interpreted language — code runs line by line without a separate compile step, so you see results instantly.
  • Why it's popular: Simple English-like syntax means beginners write working programs in their first hour, unlike Java or C++.
  • Where it's used: Instagram's backend, NASA's data analysis, ChatGPT-style AI models, and Ansible automation scripts all run on Python.
  • DevOps connection: Many automation tools (Ansible itself, AWS boto3 SDK, CI/CD scripts) are written in or scripted with Python.
  • No compiling needed: Write code → save → run. No build step like C/C++ requires.
#32
Python

Installing Python & Setup

Before writing Python code, you need Python installed on your computer. Most Linux systems already have it. Windows and Mac users download it from python.org. This card shows exact commands to check, install, and verify your setup.

# Check if Python is already installed python3 --version # Output: Python 3.11.4
  • Linux (Ubuntu/Debian): Usually pre-installed. If not: sudo apt update && sudo apt install python3
  • Windows: Go to python.org/downloads → download installer → tick "Add Python to PATH" during install (most common mistake is forgetting this box).
  • Mac: Comes pre-installed, but install the latest via brew install python3 using Homebrew.
  • Verify it worked: Open terminal/command prompt and type python3 --version — you should see a version number, not an error.
  • Choosing an editor: Beginners should start with VS Code (free) or even just a Terminal + Notepad. No need for a heavy IDE at first.
  • Running a file: Save code as hello.py then run with python3 hello.py in terminal.
#33
Python

Python Syntax Basics

Python's most unique rule: indentation (spacing) is not optional — it defines code blocks instead of curly braces {} like other languages. Get the spacing wrong and your program will literally fail to run.

# Comments start with # if True: print("Indented = inside the if block") print("Not indented = outside the block")
  • Indentation is mandatory: Use 4 spaces (not tabs) for every level. Mixing tabs and spaces causes errors.
  • No semicolons needed: Unlike C/Java, Python statements end at the newline — no ; required.
  • Comments: Anything after # is ignored by Python — use it to explain your code.
  • Case-sensitive: Name and name are two completely different variables.
  • Common beginner error: IndentationError: expected an indented block — means you forgot to indent after a colon :.
#34
Python

Variables & Data Types

A variable is a named container that stores data in memory. Python automatically detects the data type — you never declare it manually like in Java or C. This is called "dynamic typing".

name = "Devriston" # str (text) age = 25 # int (whole number) price = 99.50 # float (decimal) is_active = True # bool (True/False) print(name, age, price, is_active)
  • str (string): Text data, always wrapped in quotes — single 'text' or double "text" work the same.
  • int (integer): Whole numbers with no decimal point — positive, negative, or zero.
  • float: Numbers with decimal points, used for prices, measurements, percentages.
  • bool (boolean): Only two possible values — True or False (capital letters matter).
  • Type conversion: Use int("25"), str(25), float("9.5") to convert between types.
  • Check a type: Use type(age) — Python will tell you exactly what type a variable is.
#35
Python

Input and Output

print() displays output to the screen. input() pauses the program and waits for the user to type something — always returning it as text (string), even if they typed a number.

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: Even if user types "25", Python stores it as text "25" — wrap with int() to use it as a number for math.
  • f-strings (modern way): f"Hello {name}" — put variables directly inside curly braces. Cleanest, most readable method.
  • print() with multiple values: print(name, age) automatically adds a space between them.
  • sep and end parameters: print(a, b, sep="-", end="!") customizes spacing and line ending.
  • Common bug: Forgetting to convert input() to int/float before doing math causes TypeError: can't add str and int.
#36
Python

Python Operators

Operators perform actions on values — math operations, comparisons that return True/False, and logical combinations. Used in nearly every line of real code.

x = 10 y = 3 print(x + y) # 13 — addition print(x % y) # 1 — remainder (modulo) print(x > y) # True — comparison
  • Arithmetic: + - * / (basic math), // (floor division, drops decimals), % (remainder), ** (power, e.g. 2**3 = 8).
  • Comparison: == != > < >= <= — these always return True or False, never a number.
  • Logical: and, or, not — combine multiple True/False conditions together.
  • Assignment: = sets a value, += adds and reassigns (x += 1 is shorthand for x = x + 1).
  • Common confusion: = assigns a value, == compares two values. Mixing these up is the #1 beginner bug.
#37
Python

Conditional Statements

Conditionals let your program make decisions — running different code depending on whether a condition is True or False. This is the foundation of all program logic.

age = 20 if age >= 18: print("Adult") elif age >= 13: print("Teenager") else: print("Child")
  • if: Runs the indented block only if the condition is True. Always ends with a colon :.
  • elif (else if): Checked only if the previous if/elif was False — you can chain as many as needed.
  • else: The fallback — runs when none of the above conditions were True. Optional, but common.
  • Nested conditions: You can put an if inside another if — but keep indentation consistent or Python throws an error.
  • Real use case: Login systems, grading scripts, and even DevOps scripts use this to decide "if server is down, restart it".
#38
Python

Loops in Python

Loops repeat a block of code automatically — instead of writing print() five times, a loop does it in two lines. The two main types are for (known number of repeats) and while (repeats until a condition becomes False).

for i in range(5): print("Count:", i) # Prints Count: 0 through Count: 4
  • for loop: Best when you know how many times to repeat — looping through a range, list, or string.
  • range(5): Generates numbers 0,1,2,3,4 — starts at 0 and stops BEFORE 5, a common beginner trap.
  • while loop: Repeats as long as a condition stays True — used when you don't know the exact repeat count in advance.
  • break: Immediately exits the loop completely, even if conditions would allow more repeats.
  • continue: Skips just the current repeat and moves to the next one, without exiting the loop.
  • Infinite loop warning: A while loop with a condition that never becomes False will run forever — always make sure the condition changes inside the loop.
#39
Python

Functions in Python

A function is a reusable block of code that performs one task. Instead of repeating the same code everywhere, you write it once as a function and call it whenever needed — keeping programs organized and easy to fix.

def greet(name): print(f"Hello, {name}!") greet("Kamran") # Output: Hello, Kamran!
  • def keyword: Defines a new function. The function only runs when you "call" it by name later — defining it alone does nothing.
  • Parameters: Values passed into the function, like name above — the function uses them inside its code block.
  • return statement: Sends a value back to wherever the function was called — without return, a function gives back None.
  • Why use functions: If you find a bug, you fix it in one place (the function) instead of fixing it everywhere you copy-pasted code.
  • Default parameters: def greet(name="Guest") — lets you call greet() with no argument and it still works.
#40
Python

Python Collections

Collections store multiple values together in one variable. Python has four built-in types — list, tuple, dictionary, and set — each with different rules about order, editing, and duplicates.

fruits = ["apple", "banana", "mango"] print(fruits[0]) # apple — index starts at 0 fruits.append("grape") print(fruits)
  • List [ ]: Ordered and changeable (mutable) — you can add, remove, or edit items anytime. Most commonly used.
  • Tuple ( ): Ordered but unchangeable (immutable) — once created, items can't be edited. Used for fixed data like coordinates.
  • Dictionary {key: value}: Stores data in key-value pairs, like a real dictionary — look up a value instantly using its key, e.g. student = {"name": "Ali", "age": 20}.
  • Set { }: Unordered, and automatically removes duplicate values — useful when you only care about unique items.
  • Indexing rule: Python counts from 0, not 1 — the first item is always at position [0].
  • When to use which: Use a list for most everyday tasks, a dictionary when you need labeled data, a tuple for data that should never change.

🐍 Try Python Online

Run Python directly in your browser.


Output will appear here...

Work With Me

Need help implementing any of this?

Consulting for Linux, AWS, Terraform, Docker, CI/CD, and monitoring. Free 30-minute discovery call.