Variable scope determines where a variable can be accessed in a program. Understanding scope helps you predict how functions use variables and avoid unexpected changes or access errors.
A variable created outside any function has global scope. It can be accessed throughout the program, including from inside functions, as long as the function does not create a local variable with the same name. Global scope begins when the program starts and lasts for the duration of program execution.
All flashcards
What is variable scope?
Scope is the part of a program where a variable can be accessed.
What is a global variable?
A variable created outside any function. It can be accessed throughout the program, including from functions that do not define a local variable with the same name.
What is a local variable?
A variable created inside a function. It is available within that function and ceases to exist when the function finishes.
When is the `global` keyword needed inside a function?
Use `global` when the function needs to assign to or otherwise rebind a variable in the global scope. It is not needed merely to read a global variable.
Why should programmers avoid making every variable global?
If many parts of a program can change the same variables, unintended changes are more likely and bugs become harder to trace. Limiting scope improves clarity and maintainability.
Quiz questions
What does a variable's scope describe?Answer: The part of a program where the variable can be accessed.
Where is a variable with global scope usually created?Answer: Outside of any function.
What happens to a function's local variables after the function finishes?Answer: They no longer exist outside that function.
A global variable is named `score`. A function assigns `score = 0` without a `global` declaration. What does that assignment do?Answer: It assigns to a local variable named `score` inside the function.
Why is limiting the scope of variables useful in a large program?Answer: It reduces unintended changes and makes bugs easier to locate.
Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.