Variables in Python
Python is a dynamically typed language.
So, Python doesn't need an explicit variable declaration to reserve memory.
The variable declaration will happen automatically when we assign value to it.
Let's discuss the difference between dynamic typing and static typing.
Dynamic Typing vs Static Typing
|Dynamic Typing||Static Typing|
|Variable type checking will happen at runtime. (while executing the code).||Variable type checking will happen at compile time. (Before the actual execution).|
|As the typing checking happens in runtime the dynamically typed code can compile even it has some errors which might lead logical issues.||The statically typed code won't compile if it has any error. In order to run the code, we must fix the error.|
|Dynamically typed languages don't expect the variable declaration before using them. The variable declaration will happen automatically when we assign values to it.||Statically typed languages expect the variable declaration before assigning values to it.|
|Python, Perl, etc.||C, Java, etc.|
Assigning Values to Variable
Using = operator, we can assign values to the variable.
In Python, there are no values. Everything will be considered as objects.
In the above example, value 3 will not be directly assigned to the variable 'age'.Instead, an integer object with value 3 will be assigned to the variable 'age'.
Similarly, a string object with value "python" will be assigned to the variable 'name' and a float object with value 0.00 will be assigned to the variable 'price'.
Multiple Assignment in Python
we can assign the same object to multiple variables.
In the above example, an integer object with value 0 will be created and that will be assigned to all the variables. i.e num1, num2, num3
num1, num2, num3 will point the same memory loctaion.
Multi-value Assignment in Python
We can also assign the multiple objects to multiple variables.
In the above example,
A string object with value "python" will be assigned to the variable 'name'.
An integer object with value 300 will be assigned to the variable 'page_count'
A float object with value 254.65 will be assigned to the variable 'price'.