Conditionals
Conditionals
In the previous chapters, we explored how to store data in variables and manipulate it using basic operations. However, a program that simply executes a list of instructions from top to bottom isn't very useful. To create truly useful software a program must be able to make decisions.
Conditional logic allows a program to evaluate a situation and choose a path of execution based on whether a specific condition is True or False.
A script that tried to connect to a server regardless of whether the server is online or not would be a poor design. Instead, the script should first check if the server is online, and only attempt to connect if it is. If it isn't, the script should handle the situation gracefully, perhaps by logging an error, notifying the user, starting the server or connecting to a backup server.
This chapter covers the mechanics of Boolean logic in Python, the syntax of conditional statements, and the practical application of these tools in maintaining server health and infrastructure.
If statements
Concept: if Statement
The if statement is the most fundamental control structure in any language.
As the diagram above illustrates, the if block evaluates a condition; if the condition is True, the block of code beneath it is executed. If it is False, that code block is skipped, and the program continues executing the code that follows.
if condition:
# This code runs only if condition is True
do_something()
# This code runs regardless of the conditionNote that the line do_something() is indented, i.e. there are 4 spaces in front of the line. The colon (:) at the end of the if statement indicates that the following indented block of code is part of the if statement. There must be at least one indented line of code after the if statement, otherwise Python will throw an IndentationError.
As a practical example, consider the following.
disk_usage = 92
if disk_usage > 90:
print("ALERT: Disk space is critically low!")The code executes as follows:
- Python evaluates the condition
disk_usage > 90. - Since
disk_usageis92, the condition evaluates to True and the program enters the indentedifblock. - The alert message is printed.
Multiple paths
A single if statement can be useful, but more often, a program needs to not only check a condition, but also handle the case where the condition is False. Each if statement can be followed by an optional else statement, which is executed if the condition is False.
disk_usage = 92
if disk_usage > 90:
print("ALERT: Disk space is critically low!")
else:
print("INFO: Disk space is optimal.")When running a script that checks the health of a server, the actions in the False branch may depend on the specific environment wherein the script is running. If the server is running in a critical production environment, the script may need to send an SMS, email and Teams alert to the administrator and update a public status page to ensure customers that you're aware of the issue and working on it. However, if the server is running in a development environment, the script may only need to update the status on an internal dashboard and wait for the administrator to fix the issue during normal working hours.
This could naively be handled with a second if statement inside the else block. This is called a nested if statement, and while it works, it can quickly become difficult to read and maintain.
cpu_load = 75
if cpu_load < 30:
status = "Healthy"
else:
if cpu_load < 70:
status = "Moderate"
else:
if cpu_load < 90:
status = "Warning"
else:
status = "Critical"
print(f"Current Server Status: {status}")Note that each level of indentation requires 4 additional spaces, which is extremely difficult to read and maintain. The code above is still somewhat legible because there is just one line of code in each block. However, this is rarely the case in real-world scripts, where each block of code may contain multiple lines of code. It is therefore better to use elif statements, which are short for "else if", to handle multiple conditions.
Concept: else and elif
Should an if statement need to execute code when the condition is False, an else statement can be used to define a block of code that will run in that case.
If the else statement must also conditionally execute code, an elif statement can be used instead. If the condition for the elif statement is True, the code block beneath it will be executed; if it is False, the program will continue to the next elif or else statement (if there are any).
The number of elif statements is unlimited, but there can only be one else statement, and it must be the last statement. There can also only be one if statement, and it must be the first statement.
if condition1:
# This code runs only if condition1 is True
do_something()
elif condition2:
# This code runs only if condition1 is False and condition2 is True
do_something_else()
elif condition3:
# This code runs only if condition1 is False and condition3 is True
do_something_different()
else:
# This code runs only if both condition1, condition2 and condition3 are False
do_something_as_a_last_resort()Using elif statements, the previous example can be rewritten as follows:
cpu_load = 75
if cpu_load < 30:
status = "Healthy"
elif cpu_load < 70:
status = "Moderate"
elif cpu_load < 90:
status = "Warning"
else:
status = "Critical"
print(f"Current Server Status: {status}")Ternary operator
We've already seen how to use an if-else statement to write conditional code. However, for simple branches with one line of code each, the syntax can be rather verbose. Simple if-else statements can be written as a ternary statement.
Concept: Ternary
A ternary operator is a conditional expression that evaluates to one of two values based on a condition. It is often used as a shorthand for simple if-else statements.
A ternary expression should only be used if each branch returns a value. While this isn't a hard rule, i.e. the code doesn't crash if you break it, it is still an important stylistic/semantic rule.
result = value_if_true if condition else value_if_falseThe 02_else_statement.py example can be rewritten as follows using a ternary expression.
disk_usage = 92
message = "ALERT: Disk space is critically low!" if disk_usage > 90 else "INFO: Disk space is optimal."
print(message)
# Alternatively, you can print the message directly without storing it in a variable:
print("ALERT: Disk space is critically low!" if disk_usage > 90 else "INFO: Disk space is optimal.")Note that the alternative on the last line does not store the message in a variable, but instead prints it directly. This is allowed because the ternary expression still returns a value for both branches.