Skip to main content
Programming from zero

If and else theory + first problem: alert when a service is stopped

easyIf and else Must-do

Problem statement

Every program so far has run every line, in order, no matter what. An if statement changes that: it lets a program run one block of lines only when something is true, and a different block (the else) when it isn't. This is how a program makes a decision.

flowchart LR A{"is_running?"} -->|"true"| B["print: running normally"] A -->|"false"| C["print: ALERT service is down"] classDef check fill:#FEF3C7,stroke:#D97706,color:#92400E classDef ok fill:#D1FAE5,stroke:#059669,color:#065F46 classDef alert fill:#FEE2E2,stroke:#DC2626,color:#991B1B class A check class B ok class C alert

Common mistake: writing = (assignment) instead of == (comparison) inside the condition.

TEXT
Wrong (C++/Java): if (isRunning = false) { ... }

This doesn't compare isRunning to false, it sets isRunning to false and then checks that. Since the value being set is itself false, the if always takes the wrong branch, silently, with no error. Python avoids this entirely: writing = where a condition is expected is a syntax error, not a quiet bug.

Your task: given is_running = False, print "ALERT: service is down" if it's not running, otherwise print "Service is running normally".

Expected output:

TEXT
ALERT: service is down

Approach

The structure is the same in all three languages: check the condition, run one branch or the other.

  • Python uses if / else with a colon and indentation, no parentheses needed around the condition.
  • Java and C++ both need parentheses around the condition and curly braces around each block.
is_running = False
if not is_running:
    print("ALERT: service is down")
else:
    print("Service is running normally")