Programming from zero

Alert when a service is stopped

easyIf and else Must-do

Problem statement

A variable status holds the state of the nginx service, either "running" or something else. If it is "running", print nginx is running. Otherwise print ALERT: nginx is stopped.

Examples

Example 1

Input: status = "stopped"

Output: ALERT: nginx is stopped

Hints

Approach

Optimal

An if statement runs a block of code only when a condition is true. The condition status == "running" compares two values and gives True or False; note that == compares, while a single = assigns. The lines belonging to the if must be indented (4 spaces is standard), and the line with if ends with a colon. The else: block runs when the condition is false. Here that means any status other than "running" triggers the alert.

Python
status = "stopped"
if status == "running":
print("nginx is running")
else:
print("ALERT: nginx is stopped")

Follow-up questions

  • Make the service name a variable too, and use it in both messages.

Frequently asked questions

Python uses indentation to know which lines belong to the if. Indent every line inside the block by the same amount (4 spaces), and do not mix tabs and spaces.

A service can also be failed, restarting, or unknown. Checking for the one healthy value means every unexpected state raises an alert, which is safer for monitoring.