A variable is a container where you can store some value/data, and the name of that container is known as the Variable name so you can use that value later. In python, a variable must be defined before it is used, otherwise, you’re going to get an error message popping up.
Now, defining a variable means, you have to assign some value to the variable using the assignment operator (=).
In Python, you don’t have to mention or declare the data type of the variable, the interpreter determines is automatically during runtime. Also, you can change the type of data in a variable by re-assignment of values. This is sometimes referred as re-defining a variable.
Here, garbage collection in python comes into play. The value inside the variable ‘var’, i.e., ‘programming-articles’ is selected to garbage collection as soon as new value is assigned to var, because no variable is referencing to that object. This helps in memory management in python by throwing such objects into garbage and saving that chunk of memory.
Rules to name a variable in python –
A variable name should not be a reserved keyword of the language, i.e., some keywords like, if, for, while, etc. have meaning in a programming language.So, you must not use those words even by changing the case to avoid confusion. This means that variables are case-sensitive, i.e., var and Var are two different variable names.
A variable name must start either with a letter(a-z/A-Z) or underscore(_), i.e., a variable cannot start with a digit(0-9) or any special character.
A variable name can only contain letters, underscore and digits or a valid combination of these.
List of reserved keywords in python :
And the most basic tip for naming a variable is that a variable name should be understandable, not only to you, but for others too.
This is how we define variables in Python. Type specific methods and operations are covered with detailed articles on the individual data types.
If two or more variables contain the same value, they’re not allocated different memory space, i.e., the idea is that if they refer to the same object, why should they be be given different references, hence new memory space is not allocated to different variables having same data.
The memory address or the reference ID of a variable in python makes things clear for you.
Let’s understand how to know the address of an object in python and try to figure out how the variables with same reference affect each other:
Tip: Experiment using different object types to understand these concepts effectively.
All this makes us understand that in Python, variables do not have any data type, the type is contained in the object/value and when some type of data is assigned to a variable, python determines the type during runtime.
If you liked this article, please drop your valuable feedback comment.
Share our programming articles with your friends.