Introduction
Python allows the declaration of Local variable with the same name as Global variable. But in C#, if the variable is declared with a name, it doesn’t allow to declare a variable with the same name inside the function and within the class.
See it in action.
- public class Demo
- {
- string global = "Global Value";
- public void VariablesDemo(string global)
- {
- string global = "Local Value";
- }
-
- }
In the above C# code. the string variable ‘global’ is declared outside the function, which cannot be declared inside the function again. It gives a compile-time error.
How does it work in Python?
In Python, if we declare the variable as global and again declare inside the function with the same name, it behaves like a local variable and it won’t be considered as the global one.
Check in the below Python code.
- var = 100
- def localvariable(var):
- var = 0
- print("Local Value:", var)
- return
- localvariable(var)
- print("Global Value:",var)
Output
Local Value: 0
Global Value: 100
Variable “var = 100” defined as global and passed to a function as well. Inside function defined as “var=0”.
By seeing the output for the same, it is pretty much clear that variable declared inside doesn’t refer to the Global variable.
In order to work with the global variable, Python provides the keyword called “global” to be used inside the function followed by the variable name so that it refers to the Globally declared/defined variable.
See this in action.
- var = 100
-
-
- def localvariable():
- global var
- var = 0
- print("Local Value:", var)
- return
-
- localvariable()
- print("Global Value:",var)
Output
Local Value: 0
Global Value: 0