So you’ve set up your Python workshop and you know how to create variables and print things to the screen. That’s a fantastic start! But right now, your scripts are like a straight road; they start at one point and execute every command in order until they reach the end.

To build truly powerful and intelligent automation, your scripts need a brain. They need the ability to make decisions, choose different paths, and repeat actions. This guide will teach you how to build that brain using operators and control flow, the very heart of programming logic.

The Building Blocks: Arithmetic, Comparison, and Logical Operators

Before your script can make decisions, it needs to be able to evaluate things. Operators are the special symbols in Python that perform operations on your data. Think of them as the action words of your code.

1. Arithmetic Operators

These are the operators you already know from math class. They let you perform calculations.

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulo, which gives you the remainder of a division)
num_servers = 5 + 2   # Result is 7
remaining_disks = 10 - 3  # Result is 7
total_cost = 5 * 25.50  # Result is 127.5
disks_per_server = 15 / 3  # Result is 5.0

# Is 10 an even number? Check the remainder when divided by 2.
remainder = 10 % 2  # Result is 0, so it's even!

2. Comparison Operators

These operators are your script’s way of asking questions. They compare two values and the result is always a Boolean value: True or False.

  • == (Equal to)

  • != (Not equal to)

  • > (Greater than)

  • < (Less than)

  • >= (Greater than or equal to)

  • <= (Less than or equal to)

A very common mistake is to use a single = for comparison. Remember, = is for assigning a value to a variable, while == is for asking if two values are the same.

required_version = "3.9"
installed_version = "3.10"

print(installed_version == required_version) # False
print(5 > 3) # True
print(10 <= 10) # True

3. Logical Operators

These operators let you combine multiple comparison checks into a single expression.

  • and: Returns True only if both conditions are true.

  • or: Returns True if at least one condition is true.

  • not: Inverts the result, turning True to False and False to True.

cpu_usage = 95
memory_usage = 50

# Send an alert if CPU is high AND memory is high
print(cpu_usage > 90 and memory_usage > 80) # False

# Send an alert if CPU is high OR memory is high
print(cpu_usage > 90 or memory_usage > 80) # True

Making Decisions with if, elif, and else

Now that your script can ask questions with operators, you need a way to act on the answers. This is called control flow, and the primary tool for it is the if statement. An if statement tells your program: "If this condition is true, then execute this specific block of code."

The syntax relies on colons and indentation. The indented code block only runs when the condition is met.

status_code = 200

if status_code == 200:
  print("Success! The website is online.")

What if you want to do something else when the condition is false? That's what else is for.

status_code = 404

if status_code == 200:
  print("Success! The website is online.")
else:
  print("Failure! The website is down.")

And for situations where you have more than two possibilities, you can use elif (which stands for else if) to check multiple conditions in order.

score = 85

if score >= 90:
  print("Grade: A")
elif score >= 80:
  print("Grade: B")
elif score >= 70:
  print("Grade: C")
else:
  print("Grade: F")

Python will check each condition from top to bottom and run the code for the first one that is true.

Automating with for and while Loops

Loops are the secret to automation. They allow you to execute a block of code over and over again without copying and pasting it.

The for Loop

A for loop is perfect when you have a list of items and you want to do something for each item. Its most common partner is the range() function, which generates a sequence of numbers.

# Let's deploy 3 new servers
for i in range(3):
  # The numbers will be 0, 1, 2
  print(f"Deploying server number {i + 1}...")

The while Loop

A while loop is used when you want a loop to continue as long as a certain condition is true. You might not know how many times it will run, only when it should stop.

# Monitor disk space until it's below a threshold
disk_full_percentage = 92

while disk_full_percentage > 90:
  print(f"CRITICAL: Disk is at {disk_full_percentage}%! Deleting temp files...")
  # In a real script, you'd run a command to free up space here
  disk_full_percentage = disk_full_percentage - 1

print(f"OK: Disk space is now at {disk_full_percentage}%.")

This loop will keep running and printing the critical message until the disk_full_percentage variable drops to 90 or below.

Hands On Lab: A Simple Number Guessing Game

Let's put all these concepts together to build a fun, interactive program. The computer will think of a secret number, and we have to guess it.

# First, we need the 'random' library to generate a random number
import random

# Generate a secret number between 1 and 20
secret_number = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20.")

# We will use a while loop to keep the game going
while True:
  # Get the user's guess
  guess_str = input("Take a guess: ")
  guess = int(guess_str) # Convert the string input to an integer

  # Use an if/elif/else block to check the guess
  if guess < secret_number:
    print("Your guess is too low.")
  elif guess > secret_number:
    print("Your guess is too high.")
  else:
    print(f"Good job! You guessed my number, it was {secret_number}!")
    break # This exits the loop

This simple game uses a library, variables, a while loop to keep playing, input() to interact with the user, int() to convert data types, and an if/elif/else block to provide feedback. It's a perfect example of how these logical building blocks come together to create a complete program.

You now have the fundamental tools of logic and control flow. With these, you can write scripts that are not just lists of commands, but intelligent agents that can react, adapt, and automate complex tasks ! 🎉