InterviewSolution
| 1. |
Why is Python called dynamically typed language? |
|
Answer» Computer languages are generally classified as statically or DYNAMICALLY typed. Examples of statically typed languages are C/C++, Java, C# etc. Python, along with JavaScript, PHP etc are dynamically typed languages. First we have to understand the concept of variable. In C/C++/Java, variable is a user defined convenience name given to a memory location. MOREOVER, compilers of these languages require prior DECLARATION of name of variable and type of data that can be stored in it before actually assigning any value. TYPICAL variable declaration and assignment statement in C/C++/Java would be as follows: int x; x=10;Here, the variable x is permanently bound to int type. If data of any other type is assigned, compiler error will be reported. Type of variable decides what can be assigned to it and what can’t be assigned. In Python on the other hand, the object is stored in a randomly chosen memory location, whereas variable is just an identifier or a label referring to it. When we assign 10 to x in Python, integer object 10 is stored in memory and is labelled as x. Python’s built-in type() FUNCTION tells us that it stores object of int type. >>> x=10 >>> type(x) <class 'int'>However, we can use same variable x as a label to another object, which may not be of same type. >>> x='Hello' >>> type(x) <class 'str'>Python interpreter won’t object if same variable is used to store reference to object of another type. Unlike statically typed languages, type of variable changes dynamically as per the object whose reference has been assigned to it. Python is a dynamically typed language because type of variable depends upon type of object it is referring to. |
|