Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
In Python, if you have a global variable and a local variable with the same name, the local variable will take precedence within its scope. However, you can still access the global variable using the global
keyword. Here's an example:
global_var = "I'm a global variable" def my_function(): global_var = "I'm a local variable" print("Inside the function (local):", global_var) # Access the global variable global global_var # You need to use the 'global' keyword to refer to the global variable print("Inside the function (global):", global_var) my_function() print("Outside the function (global):", global_var)
Output:
Inside the function (local): I'm a local variable Inside the function (global): I'm a global variable Outside the function (global): I'm a global variable
In this example, we have a global variable named global_var
and a local variable with the same name inside the my_function()
function. When we print the value of global_var
inside the function, it prints the local variable's value. To access the global variable inside the function, we use the global
keyword followed by the variable name. This allows us to access and modify the global variable even when a local variable with the same name exists.
Keep in mind that using the same name for global and local variables can lead to confusion and make your code harder to maintain. It's generally a good practice to use descriptive variable names and avoid using the same name for global and local variables.
Python global variable with the same name as a local variable:
x = 10 # Global variable def example_function(): x = 5 # Local variable with the same name print(x) # Access local variable example_function() print(x) # Access global variable
How to access a global variable shadowed by a local variable in Python:
x = 10 # Global variable def example_function(): x = 5 # Local variable with the same name print(globals()['x']) # Access global variable using globals() example_function()
Using the global
keyword in Python for variables with the same name:
global
keyword to indicate that a variable with the same name should refer to the global scope.x = 10 # Global variable def example_function(): global x # Declare x as a global variable x = 5 print(x) # Access global variable example_function() print(x) # Modified global variable
Accessing global and local variables with the same name in Python:
x = 10 # Global variable def example_function(): x = 5 # Local variable with the same name print(x) # Access local variable print(globals()['x']) # Access global variable using globals() example_function()