Sign in

Intro to Computer Science / Unit 7: Functions

7.4 Scope

3 practice questionsNot yet reviewed

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 NameError because result is local to double.
  • 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?
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?
Which is the best way to get a result out of a function?

Ready for more? Take the Unit 7 test.