If two shoppers use the same checkout function, why doesn’t the first bill carry over?
You’re writing a checkout program for a school fair. It uses the same function to add up each shopper’s prices. When the second shopper arrives, what happens to the total from the first call?
You’ve already used functions with parameters. Here you pass in two prices, four pounds and three pounds. The function adds them, then returns seven to the code that called it. Let’s look at what happens to the variable that holds the sum.
The program sets the outside total to twenty and defines cost with two parameters, a and b. When you call it with four and three, it assigns seven to its local total and returns seven. The prints show seven, then twenty. A variable’s scope is where you can access it by name.
Suppose the outside total is now fifty and the function calculates a local total of nine. After the call, the main program runs print total. Which value will it display? Pick an answer.
The first call assigns seven to its local total. When it returns seven, that local variable stops existing. The second call adds four and six and assigns ten to a fresh local total. That variable stops existing when the call returns ten. Lifetime means how long a variable exists.
Keep the outside total at twenty. For the first call, six plus two gives a local total of eight. The function returns eight and that local total ends. The second call adds five and nine to get fourteen. It returns fourteen, and the outside total is still twenty.
Now the outside total is thirty. The first call uses two and five, and the second uses four and six. What does the second call return, and what is the outside total afterwards? Pick the correct pair.
When you assign the result of cost to bill, you might think the function’s local total stays stored after the call. Look at what actually gets saved: bill belongs to the caller and holds the returned value, ten. The local variable’s lifetime ends when the call returns.
In modular programming, you split a program into separate parts, such as functions. To document the interface for cost, record its name, that a and b are prices in pounds, and that it returns their sum in pounds. Now someone else can reuse the function without reading its code or rewriting the calculation.