2) Variables and expression

How to Declare a Variable

Redeclare a Variable

We can re-declare the same variable to sting in python lets do that and check if that works

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

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

Global vs Local variable

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.

Output:
different
different