Local Names
Names created inside a function are local to that function.
The name error exists while the function is running. Code outside the function
should not depend on it.
Local Names Keep Work Contained
This works:
This does not:
print(error)
Outside the function, error is not defined.
Same Local Name, Different Calls
Each function call gets its own local names:
The local name result is created separately for each call.
Local work
The function uses local names to compute each returned value.
Ready to run.
Avoid Hidden Dependencies
This function depends on an outer name:
It works, but the input is hidden. This version is clearer:
Prefer passing needed values as parameters. That makes the function easier to test.
Local Names Stay Inside the Function
Changing a name inside a function does not automatically change a name outside the function:
The final print shows 3. The assignment inside the function created a local
name.
What does the final line print?
Compute it first, then check your number.
HintSeparate the two scopes
The assignment value = 10 is inside the function. Track the outer value
separately.
SolutionThe outer value remains three
Calling set_value() creates a local value that refers to 10 only while
the function runs. The outer name still refers to 3, so the final line
prints 3.
Scope Controls Where Names Work
Local names let a function do work without leaking every intermediate value into the rest of the program.