How Different Global And Local Variables Are In Python Compared To C#

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.
  1. public class Demo  
  2. {  
  3.     string global = "Global Value";  
  4.     public void VariablesDemo(string global)  
  5.     {  
  6.         string global = "Local Value";  
  7.     }  
  8.   
  9. }  
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.
  1. var = 100  
  2. def localvariable(var):  
  3.     var = 0  
  4.     print("Local Value:", var)  
  5.     return  
  6. localvariable(var)  
  7. 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.
  1. var = 100  
  2.   
  3.   
  4. def localvariable():  
  5.     global var  
  6.     var = 0  
  7.     print("Local Value:", var)  
  8.     return  
  9.   
  10. localvariable()  
  11. print("Global Value:",var)  
Output
 
Local Value: 0
Global Value: 0