The else Branch
An if statement runs its block only when the condition is true. Often you also want to do something when it's false. That's what else (otherwise) is for:
temperature = 12
if temperature > 25:
print("Take a cap")
else:
print("Take a jacket")This prints:
Take a jacketThe condition temperature > 25 is false, so the program skips the first block and runs the block after else. The two blocks are called branches: like a path that splits in two, the program always takes exactly one of them. If the condition is true, it takes the first branch; otherwise, the second. It never runs both, and it never skips both.
You write else under its if, with the same indentation, and end it with a colon, too. Its block is indented by 4 spaces, just like the block of the if. else has no condition of its own: it takes every case the if didn't. If you give it one anyway, as in else temperature <= 25:, the program ends with SyntaxError: expected ':'. else can't stand on its own, either: it always comes right after the block of an if.
Instructions
- 1
The monitor now costs 5000, so the program prints nothing. Add an
elsebranch to theifstatement that printsI will not buy the monitor. - 2
Change
monitor_priceto3500and run the program again. Now the condition is true, so the program takes the first branch and prints onlyI will buy the monitor.