CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

PYTHON - Dynamic Typing

Python - Dynamic Typing

One of the standoutfeatures of Python languageis that it is a dynamically typed language. The compiler-based languages C/C++, Java, etc. are statically typed. Let us try to understand the difference between static typing and dynamic typing.

In a statically typed language, each variable and its data type must be declared before assigning it a value. Any other type of value is not acceptable to the compiler, and it raises a compile-time error.

Let us take the following snippet of a Java program βˆ’

PYTHON CODE
public class MyClass {
   public static void main(String args[]) {
      int var;
      var="Hello";
      
      System.out.println("Value of var = " + var);
   }
}

Here,varis declared as an integer variable. When we try to assign it a string value, the compiler gives the following error message βˆ’

PYTHON CODE
/MyClass.java:4: error: incompatible types: String cannot be converted to int
   x="Hello";
     ^
1 error

Why Python is Called Dynamically Typed?

Avariable in Pythonis only a label, or reference to the object stored in the memory, and not a named memory location. Hence, the prior declaration of type is not needed. Because it’s just a label, it can be put on another object, which may be of any type.

InJava, the type of the variable decides what it can store and what not. InPython, it is the other way around. Here, thetype of data(i.e. object) decides the type of the variable. To begin with, let us store a string in the variable in check its type.

PYTHON CODE
>>> var="Hello"
>>> print ("id of var is ", id(var))
id of var is 2822590451184
>>> print ("type of var is ", type(var))
type of var is <class 'str'>

So,varis ofstringtype. However, it is not permanently bound. It’s just a label; and can be assigned to any other type of object, say a float, which will be stored with a different id() βˆ’

PYTHON CODE
>>> var=25.50
>>> print ("id of var is ", id(var))
id of var is 2822589562256
>>> print ("type of var is ", type(var))
type of var is <class 'float'>

or a tuple. The var label now sits on a different object.

PYTHON CODE
>>> var=(10,20,30)
>>> print ("id of var is ", id(var))
id of var is 2822592028992
>>> print ("type of var is ", type(var))
type of var is <class 'tuple'>

We can see that the type ofvarchanges every time it refers to a new object. That’s why Python is adynamically typed language.

Dynamic typing feature of Pythonmakes it flexible compared toC/C++and Java. However, it is prone to runtime errors, so the programmer has to be careful.