Variable Scope
Understand where your variables live and how to access them
Learning Objectives
- Understand the difference between Local and Global scope
- Learn how to use the 'global' keyword
- Avoid common pitfalls with naming variables
Where does a variable live?
In Python, not all variables are accessible from everywhere in your code. The region where a variable is defined and can be accessed is called its Scope.
Local Scope
A variable created inside a function belongs to the local scope of that function. It only exists while the function is running.
|
|
Global Scope
A variable created in the main body of a Python file is a global variable and belongs to the global scope. Global variables are available from within any scope, next to global or local.
|
|
Naming Conflicts
If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables: one local and one global.
|
|
The global Keyword
If you need to modify a global variable from inside a function, you must use the global keyword.
|
|
return.Interactive Practice
Think about a video game. The player_score might be global, but a bonus_points variable inside a “calculate_level_end” function should probably be local.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 9 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!