if and else
Exactly one branch runs, then the program carries on
True: the if block. False: the else block. Never both.
An if statement chooses between two blocks. Follow the marks. Temp is twelve. Twelve greater than thirty is False, so the if block is skipped. The else block runs. And then the line after the whole statement: it prints fine, then done. Now with thirty one. Temp is thirty one. The test is True. The if block runs, and the else block is skipped. It prints hot, then done.
if and else · Going deeper
An if with no else
False and no else: nothing happens.
if, elif, else
The first true test wins. The rest are not looked at.
Top to bottom. First True runs. else is the fallback.
With more than two cases, add elif branches. Score is eighty five. Is it at least ninety? No. Go on. Is it at least seventy? Yes. Grade becomes merit. The chain is finished. The test for fifty is never made, though it would also be True, and the else is never reached. It prints merit.
if, elif, else · Going deeper
The same tests in the wrong order
Narrowest first, or branches become unreachable.
Check yourself
What does this print?
Several conditionals
Separate ifs are separate questions. A chain is one.
if, if: both tested. if, elif: one result.
These two programs differ by two letters. x is fifteen. Greater than five: True. Print A. The second if is a new question, so it is tested as well: greater than ten, True. Print B. The output is A, then B. Now the chain. x is fifteen. Greater than five: True. Print A, and the chain is over. The output is just A.
Several conditionals · Going deeper
Conditions joined with and and or
Each comparison first, then and or or.
Nested conditionals
A nested if is only reached through its parent
Outer True, then the inner test. Pair each else by indentation.
An if can sit inside another if. Age is twenty. Member is False. Age at least eighteen is True, so we go inside the outer block. There, the inner if asks about member. It is False, so the inner else is taken. Price becomes eight. The outer else, for children, is skipped. It prints eight.
Nested conditionals · Going deeper
Every combination
Four combinations, three paths.
Check yourself
What does this print?
Truth values
Zero and empty count as False
0, '', [], None are False. All else is True.
The condition after if can be any value, not only a comparison. These count as False: zero, zero point zero, an empty string, an empty list, and None. Everything else counts as True: any other number, even a negative one, and any string that has something in it. That includes a single space, and the text zero. They are not empty.
Truth values · Going deeper
Six faults to spot
Unreachable, redundant, misordered.
Check yourself
What does this print?
Lesson complete
You finished “Decisions: if, elif and else”
Answer the questions along the way to see your score here.