Python for Systems Engineering
Python Basics
Python's Building Blocks
Think of Python code as a set of instructions for your computer. Like any language, it has its own grammar, which we call syntax. The syntax is clean and readable, making it a great language for beginners.
At the core of Python are variables. A variable is simply a name you give to a piece of data so you can refer to it later. It's like putting a label on a box to remember what's inside. You create a variable using the equals sign (=).
# A variable named 'server_status' holds the text 'online'.
server_status = "online"
# A variable named 'cpu_load' holds the number 75.
cpu_load = 75
The data inside these boxes, or variables, comes in different forms called data types. Let's look at the most common ones you'll use.
String
noun
A sequence of characters, used for text. You create strings by wrapping text in single (' ') or double (" ") quotes.
file_path = "/etc/hostname"
error_message = 'Failed to connect'
For numbers, Python has two main types.
Integer
noun
A whole number, without any decimal points.
active_processes = 128
failed_logins = 3
Float
noun
A number that has a decimal point. The name comes from "floating-point number."
system_uptime = 99.9
average_latency = 0.085
Finally, there's a simple but powerful type for representing truth.
Boolean
noun
A data type that can only have one of two values: True or False. Booleans are essential for making decisions in your code.
is_service_running = True
backup_failed = False
Making Decisions and Repeating Actions
Scripts aren't just lists of commands executed in order. They need to react to different situations. Control structures allow you to manage the flow of your program, making it smart and dynamic.
To make decisions, you use conditional statements. The most common is the if statement. It checks if a condition is true and, if so, runs a block of code. You can add elif (else if) to check other conditions or else to run a block of code if none of the conditions are met.
memory_usage = 85 # Percentage
if memory_usage > 90:
print("CRITICAL: Memory usage is very high!")
elif memory_usage > 75:
print("WARNING: Memory usage is high.")
else:
print("OK: Memory usage is normal.")
# Output: WARNING: Memory usage is high.
Automating tasks often means doing something over and over. That's where loops come in. A for loop is great for iterating over a sequence of items, like a list of servers.
servers = ["web-01", "db-01", "app-01"]
for server in servers:
print(f"Checking status of {server}...")
# Output:
# Checking status of web-01...
# Checking status of db-01...
# Checking status of app-01...
A while loop runs as long as a certain condition is true. It's useful when you don't know exactly how many times you need to loop.
# Wait until a service is ready (a simulation)
import time
service_ready = False
attempts = 0
while not service_ready:
print("Service not ready, checking again in 1 second...")
attempts += 1 # Add 1 to attempts
time.sleep(1)
if attempts >= 3:
service_ready = True
print("Service is now ready!")
Packaging Code with Functions
As your scripts get more complex, you'll find yourself writing the same lines of code in multiple places. Functions let you package a block of code, give it a name, and reuse it whenever you need it. This keeps your code organized, readable, and easy to maintain.
You define a function using the def keyword. Functions can take inputs, called arguments or parameters, and can send back an output, called a return value.
# A function to check disk space and return a status
def check_disk_space(path, threshold):
# In a real script, you'd get the actual usage.
# Here, we'll just use a sample value.
usage = 82 # Sample usage percentage
print(f"Checking disk space for {path}...")
if usage > threshold:
return "Alert"
else:
return "OK"
# Now, let's use the function
status = check_disk_space("/var/log", 80)
print(f"Status: {status}") # Status: Alert
status_home = check_disk_space("/home", 90)
print(f"Status: {status_home}") # Status: OK
By creating a function, we can check any path with any threshold without rewriting the logic each time.
Handling the Unexpected
Things don't always go as planned. A network connection might drop, a file might be missing, or a user might enter bad data. If your script doesn't know how to handle these errors, it will crash. This is where error handling comes in.
In Python, you can use a try...except block to manage potential errors gracefully. You put the code that might fail in the try block. If an error occurs, the code in the except block is executed, and the program continues instead of stopping.
Good error handling makes your automation scripts more robust and reliable.
# Let's try to convert text to a number
user_input = "not_a_number"
try:
port_number = int(user_input)
print(f"Configuring service on port {port_number}")
except ValueError:
print("Error: Invalid port number provided. Using default port 8080.")
port_number = 8080
In this example, trying to convert "not_a_number" to an integer would normally cause a ValueError and crash the script. By catching this specific error, we can print a helpful message and fall back to a default value, allowing the script to continue its work.
Time to review what we've covered.
Let's test your knowledge.
In Python, what is the primary purpose of a variable?
Which type of loop is best suited for a situation where you need to repeat an action, but you don't know in advance how many times it needs to run?
With these building blocks, you have a solid foundation for writing simple but powerful Python scripts to automate tasks and manage systems.