BasicsLesson 2 of 16

Variables, Data Types, and Operators

Store data in variables, understand Python's core types (int, float, str, list, dict, bool), and use operators to manipulate data—the foundation of every automation script.

🧒 Simple Explanation (ELI5)

A variable is like a labeled box. You put something inside the box (a number, text, a list of items) and give the box a name so you can reference it later. Different boxes hold different things: one holds numbers, one holds text, one holds a list of servers. Python lets you put any type of data in any variable—it figures out the type automatically.

🔧 Why Do We Need Data Types?

⚙️ Technical Explanation

Variables are named references to values in memory. Python's dynamic typing means the type is determined at runtime based on the value assigned. Operators are symbols that perform operations on values: + (addition/concatenation), == (equality), and (logical AND), etc.

Core types: (1) int — integers (no decimals): 42, -10, 0. (2) float — decimal numbers: 3.14, -2.5. (3) str — text: "hello", 'world'. (4) list — ordered collection: [1, 2, 3] or ["web01", "web02"]. (5) dict — key-value pairs: {"name": "Alice", "age": 30}. (6) bool — True or False, used in conditions.

💡
String Concatenation: Single vs Double Quotes

In Python, 'hello' and "hello" are identical. Use double quotes by convention, but switch to single quotes if your string contains double quotes. F-strings (f"Hello {name}") are the modern way to embed variables in strings—prefer them over older % and .format() methods.

⌨️ Core Data Types

python
# ===== NUMBERS =====
count = 5           # int
price = 9.99        # float
total = count * price
print(f"Total: ${total}")

# ===== STRINGS =====
hostname = "web01"
port = 8080
url = f"http://{hostname}:{port}"      # F-string (modern)
print(url)

# Single vs double quotes
message = "It's working"    # double quotes when single quote appears
message = 'He said "hi"'    # single quotes when double quote appears

# ===== LISTS =====
servers = ["web01", "web02", "api01"]
ports = [8080, 8081, 9000]

# Access by index (zero-based)
first_server = servers[0]   # "web01"
last_server = servers[-1]   # "api01"

# Add/remove items
servers.append("cache01")
servers.remove("web01")

# ===== DICTIONARIES =====
config = {
    "host": "localhost",
    "port": 5432,
    "database": "prod",
    "ssl": True
}
print(config["host"])       # localhost
config["timeout"] = 30      # add new key
del config["ssl"]           # remove key

# ===== OPERATORS =====
# Arithmetic
a = 10 + 5      # 15
b = 10 - 3      # 7
c = 4 * 5       # 20
d = 20 / 4      # 5.0
e = 20 // 3     # 6 (integer division)
f = 20 % 3      # 2 (modulo/remainder)

# Comparison
x = 5
print(x == 5)   # True
print(x != 5)   # False
print(x > 3)    # True
print(x <= 5)   # True

# Logical
is_running = True
is_healthy = False
print(is_running and is_healthy)    # False
print(is_running or is_healthy)     # True
print(not is_running)               # False

# String operators
greeting = "Hello " + "World"       # concatenation
repeated = "na" * 3                 # "nanana"
print("lo" in "Hello")              # True (membership)

💼 Example (Real-world Use Case)

A DevOps script needs to process a list of VM configurations from a JSON API. Each VM is a dictionary with hostname, CPU cores, memory (GB), and running status. The script loops through the list, calculates total resources, and prints servers that are running but do not have enough memory allocated.

🧪 Hands-on

  1. Create a dictionary representing a server: include hostname, IP, port, and running status.
  2. Create a list of 3 server dictionaries.
  3. Loop through the list and print each server's hostname and whether it is running.
  4. Calculate how many servers are running (use a counter).
  5. Use operators to filter and print only servers with port > 8000.
🎮
Try It Yourself

Store a list of log levels (INFO, WARNING, ERROR), prices per level (1, 5, 10), and server names (web01, web02, api01). Create a dictionary mapping each server to its CPU cores and memory (GB). Print the average memory across all servers.

🐛 Debugging Scenario

Problem: servers[0] = "db01" seems to work, but servers[0] later returns the old value.

🎯 Interview Questions

Beginner

What is the difference between a list and a dictionary?

A list is an ordered collection indexed by position (0, 1, 2...): items[0] gets the first item. A dictionary is an unordered collection indexed by key: config["host"] gets the value for the "host" key. Use lists for sequences (servers, ports, log entries) and dictionaries for key-value data (configuration, attributes).

What is an F-string and why use it over concatenation?

F-strings (f"...") embed variables directly in strings using {variable_name}. Example: f"Server {hostname} is running". They are cleaner, faster, and more readable than string concatenation with + or older .format() methods. They are the modern Python (3.6+) standard.

Can you change a string after creating it?

No. Strings are immutable in Python. You cannot modify individual characters. You can create a new string based on the old one. That is why text processing often builds a new string rather than modifying one in place.

Scenario-based

You have a list of VM names and a separate list of their statuses (running, stopped, error). How do you associate them?

Use a dictionary or a list of dictionaries. Better: create a list of dictionaries: [{"name": "vm1", "status": "running"}, {"name": "vm2", "status": "stopped"}]. This keeps related data together, is easier to extend with more fields, and is self-documenting. Avoid parallel lists (same index in two lists)—they are error-prone.

🌐 Real-world Usage

Cloud APIs return data as JSON (parsed into dictionaries and lists in Python). Configuration files are loaded as dictionaries. Log files become lists of strings. Automation scripts heavily rely on storing, transforming, and filtering these data structures—mastering variables and operators is not optional.

📝 Summary

Variables store data, Python assigns types automatically based on values assigned. Core types: int, float, str, list, dict, bool. Operators perform arithmetic, comparisons, and logical operations. F-strings are the modern way to embed variables in text. Lists are for sequences, dictionaries for key-value data. These foundations are used in every DevOps automation script.