An if statement runs a block of code only when a condition is true.
Add elif to test more conditions, and else to catch everything
left over. This is how a script makes a decision instead of doing the
same thing every time.
cpu = 92
if cpu > 90:
print("CPU is critical")
The expression after if evaluates to true or false. When it's true,
the indented block runs. When it's false, Python skips the block and
carries on.
Python has no curly braces. The indented lines under an if are its
block, and four spaces is the standard indent. Every line at that
indent belongs to the block. The first line that dedents ends it.
if cpu > 90:
print("critical")
print("paging on-call")
print("done") # not indented, so it always runs
Chain more tests with elif, and give a fallback with else:
if cpu > 90:
print("critical")
elif cpu > 70:
print("warning")
else:
print("ok")
Python checks the conditions top to bottom, runs the first block whose
condition is true, and skips the rest. else runs only when none of
the conditions matched.
An if/elif/else chain runs at most one block. Put the tightest
condition first. If you tested cpu > 70 before cpu > 90, a value
of 95 would match the warning branch and never reach critical.