Programming from zero

Classify CPU usage as OK, warning or critical

easyIf and else Must-do

Problem statement

Monitoring tools map a number to a severity. Given cpu as a percentage, print:

  • OK if it is below 70
  • WARNING if it is 70 or more but below 90
  • CRITICAL if it is 90 or more

Examples

Example 1

Input: cpu = 87

Output: WARNING

Explanation: 87 is at least 70 but below 90.

Hints

Approach

Optimal

When there are more than two outcomes, add elif ("else if") branches between if and else. Python tests each condition in order and runs only the first block whose condition is true, then skips the rest. That is why the second check can be just cpu < 90: to reach it, cpu < 70 must already have been false. The comparison operators are <, <=, >, >=, == and !=.

Python
cpu = 87
if cpu < 70:
print("OK")
elif cpu < 90:
print("WARNING")
else:
print("CRITICAL")

Follow-up questions

  • Put the thresholds 70 and 90 in variables named WARN and CRIT.
  • Print the value too, for example cpu=87% WARNING.

Frequently asked questions

Yes. If you check cpu < 90 first, a value of 50 would print WARNING, because that condition is also true for it. Order checks from the most specific or lowest range upward.