Intro to Computer Science / Unit 7: Functions
7.4 Scope
Notes
Scope is where a variable can be used.
- A variable created inside a function is local: it exists only while that function runs.
- A variable created outside any function is global and can be read inside functions.
- Parameters are local to their function.
def double():
result = 10 * 2
double()
print(result)
- This causes a
NameErrorbecauseresultis local todouble. - Different functions can use the same variable name without interfering.
- Best practice: pass values in with parameters and send results out with
return.
Practice
Why does the code above produce an error?
Local variables disappear when the function ends.
A program sets
x = 5. A function show() sets x = 9 inside it and then prints x. The program calls show() and then runs print(x). What is displayed?Inside show, x is a new local variable set to 9. The global x stays 5.
Which is the best way to get a result out of a function?
Returning a value makes the function clear and reusable.
Ready for more? Take the Unit 7 test.