In python variables are not declared – as declared in many languages like C, C++, Java etc. Python associates variable type on the basis of value stored in it. 

Now since its not always we assign a value to a variable while writing a code, sometime value is assigned at the run-time. For example – more often we take the input from the user and assign it to a variable. In such a case variables can’t be associated with certain type (data type) while writing a code. 

It is because of this reason in python is known as dynamically typed language because it uses dynamic binding or late binding – i.e. at the run time. 

Examples

Let us understand using some coding examples:

#Let us assign some integer value to a variable X 

X=10
print(type(X))

X="Hello"
print(type(X))

Gives the output:

<class ‘int’>

<class ‘str’> 

Explanation:

Let us try to understand the code above:

  1. Line no. 3 assigns the value 10 at some memory address, and
  2. Binds the variable which is actually just a label to that memory address. That is why – type of X is displayed as <class ‘int’> which means type of X is integer.
  3. Line no. 6 re-assigns the value “Hello” to the same variable X.
    • First of all this was only possible because Python uses dynamic binding or late binding. 
    • In case of static binding used in C, C++, java etc. you cannot reassign some other data type to an existing variable. It will produce an error.
  4. Since “Hello” is a string of characters, Python stores “Hello” to some other memory location, if it does not exists. Python then binds X to either some other existing location or this new memory location holding the value “Hello”. Now the type of X is String and because of the same line 7 displays the output as <class ‘str’>

Let us improve our code to further prove our point:

X=10 
print(type(X)) 
#Let us display the memory address, X is pointing to
print(id(X))

X="Hello" 
print(type(X))
#Let us now display new memory address, X is pointing to
print(id(X))
Python Variables -Dynamic binding

Python Variables -Dynamic binding

In the above code the function id() is used to find the memory address a variable (that is passed to the function id() as an argument) is pointing to. In our case the variable X is passed as argument. 

Conclusion – Python uses dynamic binding for variables

Since value assigned to the variable X is changed from 10 to “Hello” it shows different memory address after each assignment. This proves that Python uses dynamic binding for its variables, which only act as labels pointing to some memory address holding some value that we assign to a variable.

 

Pawan Arora AdministratorKeymaster
Founder , Edukers
Teaching, Coding and Sharing is his passion. A true mentor and motivator. C/C++, Python, Java, Web Technologies (html5 / CSS/ Javascript/ JQuery,Bootstrap, nodeJS ,PHP etc.) and a WordPress enthusiast with more than two decades of experience.
follow me