In this lesson, we explore how variable scoping works in Python. By understanding the difference between local and global variables, you can write clearer and more effective code. This guide covers how variables declared inside a function are confined to that function, and when the global keyword is required.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Local Variables
Variables defined inside a function are local to that function. They cannot be accessed outside of the function’s scope. Consider the following example:result is local to the input_number function. Trying to reference result elsewhere in your code will lead to an error because its scope is strictly within the function.
Global Variables and Shadowing
It is possible to use variables that are declared outside a function (global variables) within the function body. However, if a variable with the same name exists both globally and locally, the local variable will take precedence—a concept known as shadowing.Example of Variable Shadowing
num (which is 50) instead of the global num.
Example Using Global Variable
If no local variable is defined, the function will use the global variable:Using the Global Keyword
By default, variables declared inside a function are not accessible outside of it. To modify a global variable within a function, you must declare it as global using theglobal keyword.
Declaring a variable as global allows you to modify it inside a function, making it accessible in the global scope after the function call.
input_number(), you can access the variable own_num from the global scope: