A variable is a memory location where a programmer can store a value.
Example : roll_no, amount, name etc.
Value is either string, numeric etc. Example : "Sara", 120, 25.36Variables are created when first assigned.
Variables must be assigned before being referenced.The value stored in a variable can be accessed or updated later.
No declaration requiredThe type (string, int, float etc.) of the variable is determined by Python
The interpreter allocates memory on the basis of the data type of a variable.
Python Variable Name Rules
Where the equal sign (=) is used to assign value (right side) to a variable name (left side). See the following statements :
>>>roll_no=20
>>>print(roll_no)
#prints 20
>>>emp_name="David"
>>>print(emp_name)
#prints David
#check the variable name
#initalize variable 1
roll_no=21
print(roll_no)
#prints 21
#initalize variable 2
9emp_name='David'
#prints syntax error
print(9emp_name)
The most commonly used methods of constructing a multi-word variable name are the last three examples:
>>>roll_no,name,age=19023,"David",21
>>>print(roll_no,name,age)
19023,David,21
>>>1099_filed = False
SyntaxError: invalid token
Each of the following defines a different variable:
>>> age = 1
>>> Age = 2
>>> aGe = 3
>>> AGE = 4
>>> a_g_e = 5
>>> _age = 6
>>> age_ = 7
>>> _AGE_ = 8
>>> print(age, Age, aGe, AGE, a_g_e, _age, age_, _AGE_)
1 2 3 4 5 6 7 8
Variable Type
#initalize variable 1
roll_no=21
print(type(roll_no))
#prints int
#initalize variable 2
emp_name='David'
print(type(emp_name))
#prints str
#initalize variable 3
marks=75.3
print(type(marks))
#prints float
Variable Swap
a = 2
print('a =',a)
#prints 2
b = 5
print('b =',b)
#prints 5
a = 3
print('a =',a)
#swap variable
a = b
print('a =',a)
#prints 5
b = 7
print('b =',b)