Functions
Local scope
Understand local variables and pass data between functions with parameters and returns.
Lesson 26 of 63
Reading: about 2 min
Lesson + practice: about 11 min
Difficulty: Beginner
On this page4 sections
A variable assigned inside a function is normally local to that function. Code outside cannot use that local name directly. Pass inputs in and return results out to make data flow clear.
def add_session(total, minutes):
updated_total = total + minutes
return updated_total
total = 20
total = add_session(total, 25)
print(total)45
Keep names clear
The total parameter inside add_session is local. The total variable outside receives the returned value only because the caller assigns it. Giving the names the same spelling does not automatically link them.
Why this works
The total parameter is a local name created for each call. The caller’s total changes only when the returned value is assigned back. This makes it possible to reason about a function from its inputs and output instead of relying on a hidden change elsewhere in the program.
Practice
Change add_session to return total + minutes without a temporary variable. Call it twice, assigning each returned value to total.
Does assigning updated_total inside the function create that name outside it?
Reveal answer
No. updated_total is local; the returned value is what the caller receives.
Try another case
If outer total is 20 and you call add_session(total, 5) without assigning its return, what is outer total?
Check your answer
Reveal answer
It remains 20. The function returns 25, but the caller did not store that result.
Your progress
Reveal the check answer or reach the end to complete this lesson.