if and else

Exactly one branch runs, then the program carries on

temp = 12if temp > 30: print('hot')else: print('fine')print('done')12 > 30 is Falseprints fine, donetemp = 31if temp > 30: print('hot')else: print('fine')print('done')31 > 30 is Trueprints hot, doneExactly one branch runs, then the program carries on.The condition is worked out to True or False. True runs the if block and skips the elseblock; False does the reverse. Either way the next line at the outer level runs after.

True: the if block. False: the else block. Never both.

if and else · Going deeper

An if with no else

temp = 12if temp > 30: print('hot')print('done')prints donetemp = 31if temp > 30: print('hot') print('very')print('done')prints hot, very, doneAn if needs no else. When the test is False, its block is simply skipped.The block is every line indented under the if, however many there are.else never has a condition of its own, and it must line up with its if.

False and no else: nothing happens.

if, elif, else

The first true test wins. The rest are not looked at.

score = 85if score >= 90: grade = 'top'elif score >= 70: grade = 'merit'elif score >= 50: grade = 'pass'else: grade = 'fail'print(grade)85 >= 90 is False: go on85 >= 70 is True: this block runsnever testednever reachedprints meritThe first true test wins. The rest are not even looked at.Python tries the conditions from the top. It runs the block of the first one that is Trueand then leaves the whole chain. else is the fallback, for when none was True.

Top to bottom. First True runs. else is the fallback.

if, elif, else · Going deeper

The same tests in the wrong order

score = 85if score >= 50: grade = 'pass'elif score >= 70: grade = 'merit'elif score >= 90: grade = 'top'else: grade = 'fail'print(grade)85 >= 50 is True: this block runsunreachable: anything >= 70 was caught aboveunreachable: anything >= 90 was caught aboveprints passPut the narrowest test first.The same tests in the wrong order give a wrong answer and no error. A branch that can neverrun is unreachable; a test that repeats one above it is redundant. The exam asks you to spot both.

Narrowest first, or branches become unreachable.

Check yourself

x = 7if x > 5: print('A')elif x > 6: print('B')else: print('C')

What does this print?

Several conditionals

Separate ifs are separate questions. A chain is one.

Two separate ifsx = 15if x > 5: print('A')if x > 10: print('B')else: print('C')prints A, BOne chainx = 15if x > 5: print('A')elif x > 10: print('B')else: print('C')prints ASeparate ifs are separate questions. A chain is one question.Each if starts a new decision and is always tested. elif belongs to the if above it, and istested only when everything before it in the chain was False. An else pairs with the nearest if.

if, if: both tested. if, elif: one result.

Several conditionals · Going deeper

Conditions joined with and and or

a = 4b = 9if a > 3 and b < 9: print('X')elif a > 3 or b < 9: print('Y')else: print('Z')True and False is FalseTrue or False is Trueprints YWork out each comparison, then combine them, then choose the branch.a > 3 is True. b < 9 is False, because 9 is not less than 9. Write those two words downbefore you look at and or or. Most slips are in the comparison, not in the logic.

Each comparison first, then and or or.

Nested conditionals

A nested if is only reached through its parent

age = 20member = Falseif age >= 18: if member: price = 5 else: price = 8else: price = 3print(price)20 >= 18 is True: go insidemember is False: take the inner elseprints 8A nested if is only reached through its parent.The inner if is part of the outer block, so it is tested only when age >= 18 is True.Each else lines up with the if it belongs to. Use the indentation to pair them.

Outer True, then the inner test. Pair each else by indentation.

Nested conditionals · Going deeper

Every combination

agememberPathprice20Trueouter if, inner if520Falseouter if, inner else815Trueouter else315Falseouter else3For a child, member is never looked at.Two tests give four combinations but only three paths, because the outer else does not askthe second question. The first two rows could also be written as one chain:if age >= 18 and member, elif age >= 18, else.

Four combinations, three paths.

Check yourself

a = 4b = 9if a > 3 and b < 9: print('X')elif a > 3 or b < 9: print('Y')

What does this print?

Truth values

Zero and empty count as False

Count as False00.0''[]NoneCount as True1-1' ''0'[0]zero, empty, and Noneeverything else, includinga space and the text '0'A condition does not have to be a comparison. Zero and empty count as False.if n: means "if n is not zero". if name: means "if the string is not empty". Any valuecan stand where a condition is expected, and Python reads it as True or False.

0, '', [], None are False. All else is True.

Truth values · Going deeper

Six faults to spot

FaultLooks likeWhat happensUnreachable branchelif x > 10 after if x > 5the wider test above always winsRedundant testelif x <= 5 after if x > 5else says the sameWrong orderthe widest test firstnarrower cases never get their turnSeparate ifsif, if where if, elif was meanttwo blocks run instead of oneDangling elseelse indented under the wrong ifit pairs by indentation, not by intent= for ==if x = 5:a SyntaxError, before anything runsOnly the last of these is an error. The others run, and give the wrong answer.

Unreachable, redundant, misordered.

Check yourself

n = 0if n: print('yes')else: print('no')

What does this print?

Lesson complete

You finished “Decisions: if, elif and else”

Answer the questions along the way to see your score here.

Open in a new tab