Python - Things to know before proceed - Variable Tutorial
Python variable is a container in memory (storage area) to hold value or data. In python, there is no need to assign a variable with datatype because python can detect the data type of a variable automatically.
We can assign a value to a variable by simply using the assignment operator (=).
a=10 print(a) b= 'fresherbell.com' print(b)
Here we have created a variable named a and b with no datatype and assigned the value integer 10 to variable a and string “fresherbell.com” to variable b.
Rules and Naming Convention for Variables
- Variable can contain a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example-
- Variable name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
- The variable name must not be similar to any keyword defined in the language.
- The variable name is case sensitive, i.e a and A has a different meaning.
Assigning a single value to multiple variable
a=b=c=10 print(a) print(b) print(c)
Assigning multiple values to multiple variable
a,b,c=10,20,30 print(a) print(b) print(c)
Type of Variable in Python
- Local Variable
A local variable is a variable that is declared inside the function and has scope inside the function.
def localvariable(): a=10 print (a) localvariable() #It will give error - name 'a' is not defined print(a)
In the above example, we declare a local variable inside function localvariable(), which will print a value of 10 on calling a function localvariable().
Also, we tried to print variable outside function localvariable(), which will give an error that variable a is not defined.
Hence local variables will only work within its scope.
- Global Variable
A global variable can be used anywhere in the program. Its scope is within the entire program.
The variable outside function is by default global. To declare a global variable inside a function use the global keyword behind the variable.
a=20 # Global Variable def localvariable(): global b b=10 print (b) localvariable() print(a) print(b)
A constant is a type of variable, whose value cannot be changed. Constant is always written in CAPS or UpperCase.
ABC = 10 PI = 3.14