Functions & return values
Write functions that take an input, compute, and return a value.
The same shape, now doing arithmetic
The last lesson used def and return to hand back a string. Nothing about that shape changes when the work is arithmetic instead: the function takes an input, computes, and returns one value. Interview questions are phrased this way almost every time, "write a function that takes X and returns Y", so this input-to-output contract is worth making automatic.
def square(n):
return n * n
print(square(5)) # 25
print(square(9)) # 81
square takes a number rather than a string, but the contract is identical: one value in, one returned value out. The grader still reads what you return, so a function that prints its answer and returns nothing still fails.
Pitfall: float vs floor division
Both of your exercises divide, so watch the division operator. In Python 3, / is float division and always yields a float, even when it divides evenly.
print(9 / 4) # 2.25 float division
print(9 // 4) # 2 floor division, throws away the remainder
Two traps in your formulas. First, use /, not //. Floor division like (f - 32) * 5 // 9 rounds down (// floors toward negative infinity), so a result that should be 37.777... comes back as 37. Second, keep the parentheses. f - 32 * 5 / 9 evaluates 32 * 5 / 9 first, because * and / bind tighter than -, which is not the conversion you want. Write (f - 32) so the subtraction happens before the multiply.
Interview nuance: interviewers favor pure functions, ones whose output depends only on their arguments and that cause no side effects (no printing, no mutating globals). to_celsius(212) returns 100.0 every time, so it is trivial to test, cache, and compose, as in to_fahrenheit(to_celsius(212)). A function that prints instead of returning cannot be reused or asserted on, which is exactly why "return, do not print" is the first thing a reviewer checks.
def square(n):
return n * n
print(square(5)) # 25
print(square(9)) # 81Apply
Your turn
The task this lesson builds to.
Implement to_celsius(f): convert a temperature in Fahrenheit to Celsius.
The formula is (f - 32) * 5 / 9. Return the result (don't print it).
3 hints and 4 automated checks are waiting in the workspace.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Now go the other way: implement to_fahrenheit(c) to convert Celsius to Fahrenheit.
The formula is c * 9 / 5 + 32. Return the result.
2 hints and 4 automated checks are waiting in the workspace.