DEV Community

himank
himank

Posted on

Declaration in dynamically typed:Python

python
Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable in python just an assignment statement.

A variable in C++ is a named object. Which has a particular type, that tells what values are allowed and what operations can be performed on this named object.

When we declare a variable in C++ or similar languages. The declaration statement sets aside an area of memory for holding values allowed by the data type of the declared variable. A data type defines a set of values that are allowed and a set of possible operations in case of objects. The memory allocated will be interpreted as the data type suggests. If it's an integer variable the memory allocated will be read as an integer and so on. When we assign or initialize it with some value, the value will get stored at that memory location. At compile time the initial value or assigned value will be matched with the allowed values for that data type. So we cannot mix types. Example: initializing a string value to an int variable is not allowed, and the program will not compile.

Let's see how python is different?

On the contrary, Python is a dynamically typed language. It doesn't know about the type of the variable until the code is run. So declaration is of no use. What it does is, It stores that value at some memory location and then binds that variable name to that memory container. And makes the contents of the container accessible through that variable name. So the data type does not matter. A variable can bind to a value of any data type. It will get to know the type of the value at run-time.Once it knows the data type then only valid operations can be performed on it. And it is the programmer's responsibility to ensure that the operands used, support the operations.

# This will store 6 in the memory and binds the 
# name x to it. After it runs, type of x will 
# be int. 
x = 6   

print(type(x)) 
# This will store 'hello' at some location int  
# the memory and binds name x to it. After it 
# runs type of x will be str. 
x = 'hello' 

print(type(x)) 

Output:

<class 'int'>
<class 'str'>

Top comments (1)

Collapse
 
liocnoirre profile image
LiocNoirre

Hello friends from Australia!!! Have you heard that a legendary online cаsino has opened here? I don't know how I missed this news, because I've been navigating the world of online cаsinos for a long time, and then I missed this... Don't miss this opportunity, visit the hell spin cаsino website: hellspin.casinologinaustralia.com/ . I recommend it!