How to Declare a Variable
1 2 |
a=0 print(a) #print 0 |
Redeclare a Variable
We can re-declare the same variable to sting in python lets do that and check if that works
1 2 3 4 |
a=0 print(a) #print 0 a= "xyz" print(a) |
Run the file
Output
0
xyz
That means we can redeclare the same variable to any data type in python
Variable with different data types
1 |
print("this is string" + 456) |
Output
TypeError: cannot concatenate ‘str’ and ‘int’ objects
This will give type error. As one is the string and other is number so it can not be combined.
Correct error by
1 |
print("this is string " + str(456)) |
Global vs Local variable
1 2 3 4 5 6 7 |
f= 0 def anyFunction(): f="different" print(f) anyFunction() print(f) |
Output :
different
0
- Inside a function value of f is different.
- Inside function variable defined locally.
- Variable inside a function and outside a function is considered as two different variables by python interpreter.
- If we want to change the global value of variable then we need to explicitly tell the function that variable is global
- Add global f and run again.
1 2 3 4 5 6 7 8 |
f= 0 def anyFunction(): global f f="different" # type: str print(f) anyFunction() print(f) |
Output:
different
different