3.2.10 - Local variables and modular design (Python)
Structured programs divide work into modules with clear responsibilities. You will use local variables and documented parameter/return interfaces to keep a calculation understandable, reusable and testable.
Lifetime and scope of local variables
A variable assigned inside a Python function is normally local to that function call.
Local variable
A variable belonging to a subroutine, normally accessible only there and existing for that execution of the subroutine.
def calculate_charge(quantity, unit_price):
subtotal = quantity * unit_price
return subtotal + 2
charge = calculate_charge(3, 4)
print(charge)
The local subtotal holds 12 and the returned charge is 14. The caller receives 14 through the return value; it cannot ordinarily access this local subtotal by writing that name outside the function. The parameters are also local names. Each new call gets its own calculation, so an earlier subtotal does not accidentally become the next call's starting value.
Local variables reduce interference between modules and show which data each operation owns. An identically named variable in the main program is a different variable from the local one in these examples.
A local total and the caller's total
{"code":"total = 999\ndef calculate_total(quantity, unit_price):\n total = quantity * unit_price\n return total\n\nprint(calculate_total(3, 4))\nprint(total)","instructions":"Predict both outputs and run. Change the local calculation to quantity * unit_price + 5 and run again. Explain why the main program's total remains 999."}
Clear documented interfaces
A module's interface states the information it receives and what it provides to its caller.
The interface should identify the parameter meanings, appropriate types or permitted values, and the return meaning and units. A calculation that returns a cost should not silently prompt for a new quantity or display a receipt instead of returning the cost.
def shipping_cost(weight, rate):
# weight: non-negative real kilograms; rate: real cost per kilogram
# Returns the shipping cost including a fixed charge of 2.
subtotal = weight * rate
return subtotal + 2
For weight 1.5 and rate 4, the returned cost is 8. Another programmer can use or test the function from its documented contract without relying on a hidden global variable. The local intermediate is an internal implementation detail; parameters and the return are the intentional data links. Clear contracts also reveal a mismatch such as passing grams where kilograms were expected.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account