Variables are used as containers or boxes (of real world) in our Python program. Variable stores our data.
Rules to create variables in Python.
Name starts with lower or upper case chars or underscore _
Can’t start with number
Can contain number , underscore ,char
No length restriction
Can reassign to different types.
Case sensitive
Reserved words can’t be used ( What is reserved words ?)
Must assign before using
Operations within similar variables
Scope of Variables
Video Tutorial on Variables
Data type of the variable
Each variable we create or use, belongs to one data type. In Python we can say all data types are Classes and variables are objects of these classes.
i=5
In above line we are saying variable i is an integer variable or i is an object of integer class. Different Data types in Python→
identifiers
Identifiers are name given to python objects like variables, functions, class , modules etc. We can't use reserved keywords as function names.
There are rules for the identifiers.
Only lower or upper case chars , digits and underscore are allowed. We can't start idntifier name with digit.
This code ( below ) will generate error SyntaxError: invalid syntax as varaiable name can't start with number.
4t=56
reassigned to different types
The function type() returns the variable type ( integer, float, string etc ) If a variable is used as Integer, if subsequently we assign string value to it, then the variable type will change to string.
This feature is not allowed in may other programming languages
Check the code above, since we have not assigned or used the variable my_end_name before so the line print(my_2nd_name) generates error. ( Variables are case sensitive )
Operations within similar variables
This code will generate error as we can't add integer and a string.
a=45
b="Hello"
#b=5
print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
If we un-comment the line saying b=5 , then output we will get is 50.
We can convert string to integer by using int() function and use str() to convert integer to string variable.
a='45' # a is a string variable , it is not an integer
b=42
#print(a+b) # error, as we can't add one string with integer variable
print(a+str(b)) # this is fine
print(int(a)+b) # this is fine
Scope of the variable
Can we use the variable in different programs? Answer is No , the variable is no more available after the program is terminated. Even within the program, there is a difference between availability of local variables and global variable. You can read more on local and global variables in python functions and in global local & nonlocal variables .
deleting variable
In python all are objects only. Here is one integer object a ( variable ) . We will delete the object by using del and again try to print the value.
a=6
try:
print(a) # 6
del a
print(a) # error
except NameError as my_msg:
print ("This is a NameError")
print(my_msg)
except:
print ("Some other error has occured")