Excalibur's Sheath

Python: Variables Loops & Conditionals

Mar 8, 2026 By: Jordan McGilvrayhomelab,python,automation,scripting,variables,loops,conditionals,sysadmin,cli

Python in the Homelab: Part 2 of 2

Automation often begins with simple ideas: store information, make decisions, and repeat tasks. In last week’s article, Hello World in Python: Basics and Environment Setup, we installed Python, created our first scripts, and verified that our environment was ready for development. Those first commands were intentionally simple, but they demonstrated an important point: Python makes it easy to turn small ideas into working scripts.

Once a script can run, the next step is giving it logic. Programs become useful when they can store data, evaluate conditions, and repeat operations automatically. These are the building blocks of almost every automation tool—from quick command-line utilities to large orchestration systems.

This week we will look at three fundamental concepts: variables, conditionals, and loops. Variables allow scripts to store and manipulate information. Conditionals allow programs to make decisions based on that information. Loops allow scripts to repeat actions efficiently without rewriting the same commands again and again.

Taken together, these tools allow you to write scripts that respond to real situations. A Python script can examine system data, make choices based on the results, and perform actions repeatedly across files, directories, or servers. Once you understand these building blocks, you can begin creating scripts that save real time in a homelab or server environment.

Variables

A variable stores a value that a program can reference later. Instead of repeating the same data throughout a script, you assign it to a variable name and reuse it when needed.

In Python, variables are created simply by assigning a value.

hostname = "server01"
backup_enabled = True
disk_usage = 82

Python determines the variable type automatically. Strings, numbers, and Boolean values are all handled without requiring explicit type declarations.

Variables are often used to store configuration data or results returned by commands. A monitoring script, for example, might store CPU usage in a variable and evaluate it later.

cpu_usage = 75
print("Current CPU usage:", cpu_usage)

Using variables improves readability and maintainability. If the value changes later, you only need to update the assignment rather than searching through an entire script.

Tip: Use descriptive variable names. Names like cpu_usage or backup_path make scripts far easier to understand later.

Comparisons and Basic Operators

Programs often need to compare values in order to make decisions. Python provides several comparison operators that evaluate relationships between values.

Some of the most common include:

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

These comparisons return either True or False.

disk_usage = 85
print(disk_usage > 80)

Logical operators allow multiple conditions to be evaluated together.

  • and
  • or
  • not
cpu_usage = 70
disk_usage = 85
print(cpu_usage > 80 or disk_usage > 80)

These operators become particularly useful when building monitoring scripts or automation tools that respond to multiple system conditions.

Readers familiar with command-line tools may recognize similar logic used in shell scripting, as discussed in earlier articles such as Stupid Bash Tricks – Part One.

Conditionals

Programs rarely run in a straight line. Often a script needs to make decisions based on the data it encounters. A backup script might behave differently if a directory exists, a monitoring script might respond only when a service stops running, and an automation script may branch based on command output. Conditional statements allow Python programs to evaluate conditions and choose which block of code should run.

Python has long preferred the if / elif / else chain for this type of decision-making. While Python 3.10 introduced match / case pattern matching, which can function somewhat like the switch statements found in other languages, it has not yet become common in everyday scripting environments. For the purposes of practical automation and compatibility, we will focus on the traditional conditional structures that work consistently across nearly all Python installations.

if, elif, and else

The most common conditional structure evaluates one or more conditions and executes the appropriate block of code.

disk_usage = 85
if disk_usage > 90:
    print("Critical disk usage")
elif disk_usage > 80:
    print("Warning: disk usage is high")
else:
    print("Disk usage is normal")

The program evaluates each condition in order. Once a condition evaluates to True, the corresponding block runs and the remaining conditions are skipped.

Quote: “Programs become powerful when they can decide what to do next.”

Conditionals are often used to trigger alerts, enforce safety checks, or determine whether automation tasks should proceed.

Loops

Loops allow programs to repeat actions automatically. Instead of writing the same command multiple times, a loop executes a block of code repeatedly until a condition changes.

Automation frequently relies on loops. A script may need to check multiple servers, process many log files, or iterate through directories during backups.

For Loops

A for loop iterates over a collection of items.

servers = ["web01", "web02", "db01"]
for server in servers:
    print("Checking server:", server)

Each item in the list is processed one at a time.

Numeric Loops with range()

Sometimes a script needs to repeat an action a specific number of times. Python provides the range() function for this purpose.

for i in range(5):
    print("Iteration:", i)

The loop will execute five times.

While Loops

A while loop continues running as long as a condition remains true.

count = 0
while count < 5:
    print("Count:", count)
    count += 1

While loops are useful when the number of iterations is not known in advance.

Tip: Always ensure the condition eventually becomes false. Otherwise the loop will run indefinitely.

Using Loops in Practice

Understanding loop syntax is helpful, but their real power appears when scripts operate on collections of data.

Iterating Over Lists and Data

Many automation tasks involve processing lists of items.

users = ["alice", "bob", "charlie"]
for user in users:
    print("Creating account for", user)

The same logic can apply to files, directories, or network hosts.

Scaling Scripts Across Systems

Loops allow scripts to scale easily. Instead of repeating commands manually for each system, a loop processes each host automatically.

servers = ["server01", "server02", "server03"]
for server in servers:
    print("Pinging", server)

This idea becomes especially useful when combined with command-line tools and networking utilities described in articles like Mastering Network Tools.

Combining Loops and Conditionals

Automation scripts become truly powerful when loops and conditionals work together.

Evaluating Values in Loops

A script may loop through data and evaluate conditions for each item.

disk_values = [40, 55, 90, 70]
for value in disk_values:
    if value > 80:
        print("Warning: disk usage high:", value)

Each value is evaluated individually.

Monitoring-Style Logic

This pattern is common in monitoring scripts.

servers = ["web01", "web02", "db01"]
for server in servers:
    status = "online"
    if status != "online":
        print("Alert:", server, "is offline")

The script checks each server and responds only when a problem appears.

Readers interested in monitoring and auditing tools may also want to review File Auditing and Security Tools, which discusses system integrity and monitoring utilities available on Linux systems.

Common Beginner Errors

When learning Python, several mistakes appear frequently.

One common issue is incorrect indentation. Python uses indentation to define code blocks, so consistent spacing is critical.

Another frequent problem involves infinite loops. A loop that never updates its condition will run forever.

while True:
    print("This never stops")

Finally, beginners sometimes misuse comparison operators. Remember that = assigns values, while == compares them.

Tip: When debugging scripts, print variable values to verify that conditions behave as expected.

Summary

Variables, conditionals, and loops form the core building blocks of Python programming. Variables allow scripts to store and reference information, making programs easier to read and maintain. By assigning values to meaningful names, scripts become more adaptable and easier to modify as requirements change.

Conditionals give programs the ability to make decisions. Using if, elif, and else, a script can evaluate system data and respond appropriately. This allows automation tools to behave differently depending on system conditions, command results, or user input.

Loops allow scripts to repeat actions efficiently. Instead of manually running commands for every file or server, loops handle repetition automatically. Combined with lists and data collections, loops allow automation scripts to scale across multiple tasks or systems.

Together, these tools form the foundation of practical scripting. Once a script can store data, make decisions, and repeat operations, it becomes capable of real automation. In the next article we will build on these concepts by exploring file handling and data processing, allowing Python scripts to read, analyze, and manipulate real system data.

More from the "Python in the Homelab" Series: