A variable is a named identifier which contains a value. It always points to a memory location. In python variables do not have any type such as int, float etc. They are dynamically typed which means their type is decided at execution time according to the value they hold.
A variable is created at the time when a value is assigned to it. Example,
value = 4 #variable of integer type name = “codippa” #variable of string type
Variable declaration rules
A variable name defines the purpose of a value in a program. Example, a variable which holds a name can be declared as name or emp_name or person_name etc. However, this depends on the programmer and there are no rules for this. But there are some rules which should be followed while variable declaration. A variable name should
- start with a letter or an underscore. It cannot start with a number.
- contain only alphanumeric characters. No special characters are allowed.
Examples of valid variable names are name123, emp_id, address2, _version etc.
Examples of invalid variable names are 123name, emp#, a2ddress etc.
Variable names in python are case-sensitive. Address and address are two different variables.
If you declare an invalid variable name, then you get SyntaxError: invalid syntax at run time.
Printing the value of a variable
Python provides a built-in function named print which prints the value of a variable as shown below.
name = "codippa" print(name) # will print codippa
Getting type of a variable
Python’s type function can be used to determine the type of any variable, that is the type of value contained in a variable. Examples,
name = “codippa” type(name) # will print <class 'string'> count = 1 type(count) # will print <class 'int'>
Multi variable assignment
Python allows assigning a value to multiple variables simultaneously, that is, same value can be assigned to multiple variables at the same time as shown below.
first = second = third = 5 print(first) # will print 5 print(second) # will print 5 print(third) # will print 5
Python also allows assigning different values to different variables at the same time, that is, different values(of same or different type) can be assigned to different variables in a single statement as shown below.
num, name, count = 2, "codippa", 5 print(num) # will print 2 print(name) # will print codippa print(count) # will print 5