Lesson 3 of 6
Decisions and functions
Code chooses with if, elif and else, and combines tests with and, or and not. A function wraps the choice in a name, hands back one value with return, and can stop a walk the moment the answer is known.
Predict which branch of an if, elif, else chain runs, and order the tests so the right one does
Write a two-way choice in one line with a conditional expression
Combine tests with and, or and not, with the safety check on the left
Write a function that returns its answer instead of printing it
Stop a walk with an early return, put the not-found answer after the loop, and tell return from break
State a function's promise in a docstring and choose tests at its edges
Your pipeline tags every day by its order count: 20 or more is busy, 10 to 19 is normal, fewer is quiet. In SQL that is one CASE WHEN. In Python it is a decision: a few lines that look at a value and choose what to do.
Next you want that tag in ten places, checked by tests, readable by a teammate. That calls for a function: a named piece of code that takes inputs and hands back one answer.
Most interview solutions are a walk, some decisions, and a function around them. The last lesson built the walk. This one builds the other two pieces, one line at a time, and puts all three together in Fizz Buzz, a classic warm-up.
Choosing one branch: if, elif, else
How does code choose? It asks a yes-or-no question, and the answer is a value: True or False. These two values have the type bool (short for Boolean), one of the five types from the first lesson. The usual way to ask is a comparison. With x = 7 and y = 10:
| Comparison | Asks | Gives |
|---|---|---|
x == y | is x equal to y? | False |
x != y | is x different from y? | True |
x < y | is x less than y? | True |
x <= y | is x less than or equal to y? | True |
x > y | is x greater than y? | False |
x >= y | is x greater than or equal to y? | False |
== asks; = assigns. x == 10 asks whether x equals 10. x = 10 makes the name x refer to 10. Python refuses if x = 10: with a SyntaxError, so this mix-up at least fails loudly.
An if runs its indented lines only when its test is True. Add elif (short for "else if") for another test and else for everything left over, and you have a chain. Python asks the tests from the top and runs only the first branch whose test is true. The rest of the chain is skipped, even tests that would also be true. The else is optional: without it, a value that fails every test runs nothing in the chain.
Here is the day tag on three days. Before you step through, guess which print runs for the 12, and whether the elif line is ever asked about the 30.
orders = [12, 30, 7]for x in orders:if x >= 20:print(x, "busy")elif x >= 10:print(x, "normal")else:print(x, "quiet")
(nothing printed yet)So the order of the tests is part of the logic. 30 would pass both tests, but only the first branch ran. If the chain asked x >= 10 first, 30 would come out normal and the busy branch could never run. The rule: put the narrowest test first. The narrowest test is the one true for the fewest values: every value that passes x >= 20 would also pass x >= 10, so x >= 20 goes first.
Separate if statements are separate decisions. Only elif and else attach to the chain above them. Two if lines in a row are both asked, and both bodies can run:
x = 30
if x >= 20:
print("busy")
if x >= 10:
print("normal")
This prints busy, then normal, because the second if starts a new decision and asks about 30 again. Change the second if to elif and it prints only busy.
Now predict a chain whose tests are in the wrong order.
This chain asks its tests in a different order from the trace above. Type exactly what it prints, one line per print.
for x in [25, 12, 4]:
if x >= 10:
print(x, "normal")
elif x >= 20:
print(x, "busy")
else:
print(x, "quiet")
One line for a two-way choice
When an if/else only decides which value a name gets, Python can say it in one line. With x = 7, these four lines label it:
if x % 2 == 0:
label = "even"
else:
label = "odd"
This one line does the same:
label = "even" if x % 2 == 0 else "odd"
Both versions make label refer to "odd", because 7 % 2 is 1. Read the one line as a sentence: "even" if the test is true, else "odd". It is called a conditional expression. Python asks the test first, then works out only the side it chose. The whole thing is a value, like x + 1, so it can go wherever a value can: print(x, "even" if x % 2 == 0 else "odd"), or return a if a > b else b. In SQL it is a CASE WHEN with one WHEN and an ELSE. It has one test and two outcomes; for three, such as busy, normal and quiet, write the chain.
Each print uses a conditional expression. Type exactly what this prints, one line per print.
for x in [4, 7, 0]:
print(x, "even" if x % 2 == 0 else "odd")
a = 3
b = 8
print(a if a > b else b)
Combining tests: and, or, not
Some decisions need two facts at once: a day that is busy and also a weekend, a reading that is negative or missing. and, or and not combine True and False into one answer:
a and bisTrueonly when both sides areTrue.a or bisTruewhen at least one side isTrue.not aflips the value:not TrueisFalse.
With x = 12: x >= 10 and x % 2 == 0 is True, because 12 is at least 10 and even (x % 2 is the remainder after dividing by 2, so x % 2 == 0 means even). x >= 20 or x % 2 == 0 is also True, because the second side holds. not (x >= 10) is False.
When one test mixes and with or, add parentheses. Python works out and before or, the way it works out * before +, so a or b and c means a or (b and c). Parentheses show the grouping you meant, so nobody has to remember the rule.
Comparisons can also chain. 10 <= x < 20 means 10 <= x and x < 20, so it is true for 10 through 19. Later modules check that a position is inside a grid this way: 0 <= r < rows.
Python stops as soon as it knows the answer. This is called short-circuiting. In a and b, a false a already makes the whole answer False, so Python never looks at b. In a or b, a true a already makes it True, so b is skipped. The main use is safety: the left side can guard the right side.
The trace asks whether the first day was busy, on a list with no days at all. Reading orders[0] there would fail with an IndexError, the error Python raises for a position that does not exist. Before you step through, guess: does this program stop with an IndexError, or print a line?
orders = []has_orders = len(orders) > 0if has_orders and orders[0] >= 20:print("busy first day")else:print("no busy first day")
(nothing printed yet)Put the guard on the left. The last lesson's while loop did the same: while i < len(orders) and orders[i] <= 20 checks that the position exists before reading it. Swap the sides and see what happens.
The two sides of and are swapped from the trace above:
orders = []
if orders[0] >= 20 and len(orders) > 0:
print("busy first day")
else:
print("no busy first day")
What happens when it runs?
Choose one answer, then check.
not is the usual way to test for an empty list. In an if or while test, Python counts an empty list, the number 0, the empty string "" and None as false, and a non-empty list or any other number as true. So if not orders: reads "if there are no orders", a common first line for handling the empty case before a walk.
not also makes a guard for or: "the list is empty, or its first day is quiet". Predict it on three lists.
not orders is True exactly when orders is the empty list. Type exactly what this prints, one line per print.
orders = []
print(not orders or orders[0] < 10)
orders = [4, 9]
print(not orders or orders[0] < 10)
orders = [15]
print(not orders or orders[0] < 10)
Recap: a comparison gives True or False, a chain runs the first branch whose test is true, and and and or stop as soon as the answer is known. Order matters in both: the narrowest test first in a chain, the guard on the left of an and or an or.
Functions: hand the answer back
You have already filled in functions: smallest and the problems in the last lesson. This section slows down to show what a function does, because interview solutions are functions: you write the code once, call it with different inputs, and tests check what comes back.
A function is a named piece of code with inputs and one output. def double(x): defines a function named double with one parameter, x: a name for the input. A call such as double(4) runs the function's body (its indented lines) with x naming the value passed in, which is called the argument. return ends the call and hands a value back, and that value takes the place of the call in the line that made it.
A function can take several parameters, separated by commas. def add(a, b): called as add(2, 3) gives a the 2 and b the 3: arguments match parameters by position.
Before you step through, guess what the last line prints. In the trace, watch the boxes of names: each call gets its own box, labelled with the function's name, and the box disappears when the call returns.
def double(x):result = x * 2return resulta = double(4)b = double(a) + 1print(a, b)
(nothing printed yet)print shows a value; return hands it back. A function that prints its answer looks finished, because the right number appears on screen. But the code that called it gets nothing back that it can use. Before you step through, guess what week holds at the end.
def total(nums):s = 0for x in nums:s += xprint(s)week = total([3, 4])print(week)
(nothing printed yet)Check yourself on a program that does both.
One function prints and one returns. Type exactly what this program prints.
def show_double(x):
print(x * 2)
def double(x):
return x * 2
a = show_double(5)
b = double(5)
print(a, b)
return also ends the call at once. No later line of the function runs in that call. So a function can return from inside each branch of a chain. Here is the day tag from the opening, as a function:
def label(x):
if x >= 20:
return "busy"
elif x >= 10:
return "normal"
else:
return "quiet"
label(12) hands back "normal", and the caller decides what to do with it: print it, store it, or compare it in a test.
Recap: a function takes arguments through its parameters, runs in its own box of names, and hands back one value with return. Without a return, it hands back None.
Now write one. In the leap-year rule, the order of the tests decides the answer.
Write is_leap(year), which returns True when year is a leap year and False when it is not. The calendar states the rule from the general case to its exceptions:
- A year that is a multiple of 4 is a leap year,
- except a multiple of 100, which is not,
- except a multiple of 400, which is a leap year after all.
So 2024 and 2000 are leap years, and 2023 and 1900 are not. year % 4 == 0 asks whether 4 divides year with nothing left over. Write the chain so that each year stops at the rule that decides it. Then press Watch it run to see which branch 1900 takes.
raise NotImplementedError, then press Run tests. Each check says what it expects.Early return: stop when you know
A sensor feed should never go negative, and you want the position of the first bad reading. Once you find one, the rest of the list cannot change the answer, so there is no reason to keep walking.
A return inside a loop stops the walk the moment the answer is known. It ends the whole function, loop included. If the loop finishes without returning, nothing was found, so the "not found" answer goes after the loop. Here that answer is -1, a common "not found" value in interview problems: a position counted from 0 is never negative, so -1 cannot be mistaken for a real one.
The trace calls the function twice: once on a list with negative numbers, once on a list without. Before you step through, guess how many numbers the first call looks at.
def first_negative(nums):for i in range(len(nums)):if nums[i] < 0:return ireturn -1print(first_negative([4, 7, -2, 5, -8]))print(first_negative([3, 1]))
(nothing printed yet)Here is the search in the four questions this course asks of every algorithm: the order of the walk, the notebook of state it keeps, the promise that notebook keeps, and the cost.
The promise is what makes this correct. When line 4 returns i, nums[i] is negative and no number before it is, so i is the first. When the loop runs out, the promise covers every position, so no number is negative and -1 is right.
Test the answer with == -1. if not first_negative(nums): looks like "if none was found", but it is wrong both ways. A negative number at position 0 returns 0, which counts as false, and -1 counts as true. Check before you use the answer as a position, too: nums[-1] is legal Python and quietly reads the last item.
Here is first_negative from the trace above:
def first_negative(nums):
for i in range(len(nums)):
if nums[i] < 0:
return i
return -1
How many times does the test nums[i] < 0 run during the call first_negative([5, 0, 3, -4, -1])? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The mirror image returns False at the first number that breaks a rule, and True only after the loop has checked them all.
Put the lines in order to build all_positive(nums), which returns True when every number in nums is above 0, and False as soon as one is not. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
for x in nums:else:return Trueif x <= 0:return Truereturn Falsedef all_positive(nums):
break and continue change a walk without ending the function. break leaves the loop at once, and the lines after the loop still run. continue skips the rest of this pass and moves on to the next item. return leaves the whole function, so when the answer is ready, it is usually the clearer choice. You will meet break again in later modules, in loops that stop early but still have work to do afterwards.
continue skips the rest of this pass and takes the next item. break leaves the loop. Type exactly what this prints, one line per print.
for x in [12, 0, 30, 7]:
if x == 0:
continue
if x >= 20:
break
print(x)
print("done")
A function is a promise
How do you know a function is right? Start by saying exactly what it promises: what goes in and what comes out. Write that in a docstring, a string in triple quotes on the first line of the body. Python stores it with the function, and every reader sees the contract before the code.
Then check the promise with tests: calls on inputs whose answers you already know. A test is ordinary code. It calls the function, compares what comes back with the promised answer, and reports. This trace runs one test on an input that often breaks a loop: the empty list. Before you step through, guess how many times line 4, the test inside the loop, runs.
def first_negative(nums):"""Return the position of the first negative number, or -1 if none."""for i in range(len(nums)):if nums[i] < 0:return ireturn -1def test_empty():"""An empty list has no negative number: expect -1."""got = first_negative([])if got == -1:print("ok: the empty list gives -1")else:print("FAIL: expected -1, got", got)test_empty()
(nothing printed yet)The tests in this lab work the same way, with one helper, expect_equal. expect_equal(first_negative([]), -1) stays quiet when the two values match and stops with a message showing both values when they do not. Every code exercise and problem here runs a list of such tests, each named for the requirement it checks.
Good tests aim at the edges, where code breaks: the empty list, a single item, the answer at the very start or the very end, and values sitting exactly on a boundary. A test at 25 cannot tell x >= 20 from x > 20; a test at exactly 20 can.
Here is label again, now with a docstring that states its promise:
def label(x):
"""Tag a day with x orders (x is 0 or more): busy, normal or quiet."""
if x >= 20:
return "busy"
elif x >= 10:
return "normal"
else:
return "quiet"
On paper, list the inputs you would test it with, each with the answer it should give. Aim for inputs that would expose a mistake, not inputs that are comfortable. Then reveal the steps one at a time and compare.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Fizz Buzz: every piece at once
Can you put a walk, a chain and a returned answer together? Fizz Buzz needs every piece of this lesson. It is a counting game: say the numbers from 1 to n, but say "Fizz" for a multiple of 3, "Buzz" for a multiple of 5, and "FizzBuzz" for a multiple of both. Four pieces you already have:
- "Multiple of" is a remainder test.
i % 3is the remainder after dividingiby 3, soi % 3 == 0is true exactly when 3 dividesi:9 % 3is 0 and10 % 3is 1. - The walk is 1 to
n.range(1, n + 1)gives 1, 2, ...,n, because a range stops before its second number. - The decision is a four-way chain. 15 is a multiple of 3 and of 5. Which test has to come first?
- The answer is a returned list of strings.
str(7)turns the number 7 into the text"7". Append one string per number and return the list; do not print it.
The whole problem is the order of the chain. The "both" test goes first, because a chain runs only the first true branch and 15 would otherwise stop at "Fizz". The other traps are the ones from this lesson and the last: range(n) starts at 0, not 1, and a version that prints each word hands back None and fails every test.
Last, practice saying how you know your code works. These are the words you will need when there is no run button.
You have written first_negative in a round with no run button, and the interviewer asks: "How do you know it works?" Write what you would say: which inputs you would trace, in what order, and what you would check on each.
Saved in this browser as you type.