Python Basics β Variables, Types & Control Flow
The essential syntax you'll use in every automation script you write.
Every automation script is built from the same handful of ideas: storing values, choosing between data types, grouping data in collections, making decisions, and repeating work. This lesson covers all of them.
π― Learning Objectives
By the end of this lesson you will:
- Use variables and Pythonβs core data types
- Work with lists and dictionaries
- Write conditionals (
if/elif/else) - Loop with
forandwhile
Variables and Data Types
Python figures out the type for you β no declarations needed:
name = "web-server-01" # string
cpu_count = 4 # integer
load_average = 0.75 # float
is_healthy = True # boolean
print(name, cpu_count, load_average, is_healthy)Collections: Lists and Dictionaries
These two structures carry most DevOps data (servers, configs, API responses).
A list β an ordered sequence:
servers = ["web-01", "web-02", "db-01"]
print(servers[0]) # web-01
print(len(servers)) # 3
servers.append("web-03") # add oneA dictionary β key/value pairs (just like JSON):
server = {
"name": "web-01",
"cpu": 4,
"region": "eu-west-1",
}
print(server["region"]) # eu-west-1π‘ Dictionaries = JSON
API responses and config files are almost always key/value data. Python dictionaries map onto JSON directly, which is why they show up constantly in DevOps scripts.
Making Decisions: if / elif / else
load = 0.85
if load > 0.9:
print("CRITICAL: scale up now")
elif load > 0.7:
print("WARNING: load is high")
else:
print("OK")β Indentation is the syntax
Python has no braces β indentation defines blocks. Use 4 spaces consistently. Mixing tabs and spaces is the classic beginner error and will raise an IndentationError.
Loops
Loop over a list with for:
servers = ["web-01", "web-02", "db-01"]
for server in servers:
print(f"Checking {server}...")Repeat while a condition holds with while:
attempts = 0
while attempts < 3:
print(f"Retry {attempts + 1}")
attempts += 1π‘ f-strings
f"Checking {server}" is an f-string β it drops variables straight into text. Itβs the cleanest way to build log lines and messages, and youβll use it everywhere.
π§ͺ Hands-on Lab
Server Health Reporter
- Create a list of 3 server names.
- Loop over them and print
"<name> is being checked"using an f-string. - Make a dictionary describing one server (name, cpu, region) and print its region.
- Add an
if/elsethat prints"scale up"when aloadvariable is above0.8.
π§ Knowledge Check
Which Python data structure best represents a JSON object with key/value pairs?
What defines a block of code in Python (e.g. the body of an if statement)?
πΌ Interview Preparation
What's the difference between a list and a dictionary, and when would you use each?
Summary
Youβve covered variables, data types, lists, dictionaries, conditionals, and loops β the foundation of every script. Next, we put it to work automating real DevOps tasks.