What are variables ?
Variables are used to store data. A variable is a name in which values ββare stored. The name of a variable can be understood as a container. Just like any item is stored in a box. Similarly, to store data in computer memory, the data is stored in variables. If we store the data like this in the memory, then it will be very difficult to access that data, but by using the variable in which that data is stored, we can easily work on the data. The data stored in variables can be any text, number or anything. Below some values ββhave been stored in some variables.
a = 15
b = 1.14
a and b are variables which have the values ββ15 and 1.14 stored in them. In Python language = (Operator) is used to store the value inside a variable.
Object Reference / Memory Allocation
The way variables work in Python is completely different from other programming languages
ββ(like C, C++, or Java). To understand this, we need to understand the difference between a
'container' and a 'tag'. Let's understand this in depth with very simple words and examples:
In C / C++ / Java : A variable is like a box or container. When you write int
x = 10;, a box named 'x' is created in memory and '10' is placed in it.
In Python : A variable is not a box, but a label or tag (Tag/Pointer). When you
write x = 10, Python first creates an object named '10' in memory and then binds a string or tag
named x to that object.
Let's say we write a few lines of code. Let's see what's happening in Python's memory in the background:
# Case 1: Creating a New Variable
x = 10
# Case 2: Assigning one variable to another
y = x
case 1 : Python created an object in memory with the value 10. Now x points to
that 10 object.
case 2: No new 10 object will be created. Instead, a new tag named y will be
attached to the old 10 object. This means that both x and y now point to the same object.
Rules for Creating Variable Names
To create variables in Python Programming Language, some rules have to be followed. These
rules are given below:
1. There should not be any space in the name of any variable because by giving space the words
get divided into parts and Python is not able to know about the correct variable.
2. While creating the names of variables, no spatial symbol (#, space, @, comma) is used in the
variable name.
3. Space is not used in the name of variables, but if the name is very long, underscore (_) is
used in place of space.
4. Variables are case-sensitive, that is, both a and A are different variable names and they
have no relation with each other.