G
GuideDevOps
Lesson 2 of 15

Python Basics

Part of the Python for DevOps tutorial series.

Variables and Data Types

Basic Variables

Action:

hostname = "web-server-01"
port = 8080
cpu_usage = 85.5
is_running = True
 
print(f"Host: {hostname}, Port: {port}, CPU: {cpu_usage}%, Running: {is_running}")

Result:

Host: web-server-01, Port: 8080, CPU: 85.5%, Running: True

Collections

Action:

# List (ordered, mutable)
servers = ["web-1", "web-2", "db-1"]
servers.append("cache-1")
print(f"Servers: {servers}")
 
# Dictionary (key-value)
config = {
    'host': 'localhost',
    'port': 5432,
    'timeout': 30
}
print(f"DB Port: {config['port']}")

Result:

Servers: ['web-1', 'web-2', 'db-1', 'cache-1']
DB Port: 5432

Control Flow

If Statements

Action:

cpu_usage = 85
 
if cpu_usage > 80:
    print("ALERT: High CPU usage!")
elif cpu_usage > 50:
    print("Warning: Medium CPU usage")
else:
    print("CPU usage normal")

Result:

ALERT: High CPU usage!

Loops

Action:

servers = ["web-1", "web-2", "db-1"]
 
for server in servers:
    print(f"Checking health of {server}...")

Result:

Checking health of web-1...
Checking health of web-2...
Checking health of db-1...

Functions

Action:

def get_status(service_name, port=80):
    return f"Service {service_name} is listening on port {port}"
 
status = get_status("nginx", 443)
print(status)

Result:

Service nginx is listening on port 443

String Operations

Action:

command = "ls -la /var/log"
 
print(f"Uppercase: {command.upper()}")
print(f"Parts:     {command.split()}")

Result:

Uppercase: LS -LA /VAR/LOG
Parts:     ['ls', '-la', '/var/log']

Summary

  • Lists are used for ordered sequences (e.g., server lists).
  • Dictionaries are perfect for configuration and metadata.
  • f-strings are the modern way to format strings in Python.
  • Functions help modularize your automation scripts.