Functions That Return Answers
You met functions in Phase I — you taught the turtle a trick with def and called it. Those functions did something (drew a shape). Today’s functions answer something: they compute a value and hand it back with return, so you can use the answer however you like. This is how programmers package up useful logic — and how you’ll transform data in Phase III.
return: hand back an answer
A function can return a value. Whatever you return becomes the result of calling it:
add(2, 3) runs the function, which returns 5. We store that in answer and print it. The function gave us a value to use.
Try it 🎯
- Write a
multiply(a, b)function and use it to print6 × 7. - Call
addinside aprint:print(add(10, 20)).
return is not the same as print
This catches people. print shows a value on screen; return hands it back so the rest of your program can use it. Compare:
Because double_and_return hands back a value, we can do math with it (x + 1). A function that only prints can’t be used that way.
Combining returned values
The real power: use one function’s answer inside another expression:
You wrote the “how to compute an area” logic once, then reused it and combined the results.
A function that decides
A function can contain if and return different answers:
Predict it 🔮
What does this print? Notice the function uses return, and we print the result:
(25 — square(4) is 16, square(3) is 9, and 16 + 9 = 25. Because each call returns a number, we can add them.)
Fix the bug 🐞
This triple function is supposed to return three times its input, but the result comes out as None. It’s missing one keyword:
(The function computes n * 3 but never hands it back, so it returns nothing (None). Add return: return n * 3.)
Your mission 🚀
Write a function is_even(n) that returns True if a number is even and False if it’s odd. (Hint: a number is even when n % 2 == 0.) Then test it on a few numbers:
What you learned today
returnhands a value back from a function so you can use it.returnis different fromprint— one gives back a value, the other just shows it.- You can combine returned values in bigger expressions, and
returndifferent things from insideif. - Functions let you write logic once and reuse it everywhere — the building block of bigger programs.
Next time is a project: a chatbot that reads what you type and replies, using everything from this phase. 🤖
Comments