Build a service health report from a list of servers
Problem statement
This mini script combines four things you already know: a dictionary, a loop, conditions and formatted output.
You have the CPU usage of four services. Classify each one:
90or more: critical70or more (but under90): warning- anything lower: healthy
Then print one line per service and a summary line with the totals.
Common mistake: checking the smaller limit first.
Wrong:if value >= 70: label = "warning"elif value >= 90: label = "critical"A value of 95 is already >= 70, so it is labelled warning and the critical branch is never reached. Check the biggest limit first.
Your task: use the CPU usage api 45, cache 72, db 95 and web 30. Print each service as <name>: <value>% <label>, then print Summary: <n> healthy, <n> warning, <n> critical.
Expected output
api: 45% healthycache: 72% warningdb: 95% criticalweb: 30% healthySummary: 2 healthy, 1 warning, 1 criticalApproach
Loop over the dictionary, pick a label with if / elif / else, and count each label:
- Python:
for name, value in cpu.items():gives the key and value together. - Java:
LinkedHashMapwithfor (Map.Entry<String, Integer> entry : cpu.entrySet()). - C++:
std::mapwithfor (const auto& entry : cpu), usingentry.firstandentry.second.
Note on order: the keys are added in alphabetical order, so Python, Java's LinkedHashMap and C++'s std::map all print the services in the same order.
cpu = {"api": 45, "cache": 72, "db": 95, "web": 30}
healthy = 0
warning = 0
critical = 0
for name, value in cpu.items():
if value >= 90:
label = "critical"
critical += 1
elif value >= 70:
label = "warning"
warning += 1
else:
label = "healthy"
healthy += 1
print(f"{name}: {value}% {label}")
print(f"Summary: {healthy} healthy, {warning} warning, {critical} critical")