How do we declare variable in Python?

PythonServer Side ProgrammingProgramming

Short answer is there is no need to declare variable in Python.

Following is the description in more detail.

Statically typed languages (C, C++, Java, C#) require that name and type declaration of variable to be used needs to be declared before using it in program. Respective language compiler ensures that appropriate data is stored in the variable. For example in C, if programmer intends to store integer constant in a variable, it must be declared as:

int x;

After declaration, assignment or user input may be provided to it. If the value assigned to it is apart from integer, compiler will complain about type mismatch error.

x=10; // this is valid assignment
x = “Hello”; // this generates type mismatch error

Python is dynamically typed language. In fact, in Python data object of a certain type (number, string, Boolean etc.) is stored in a particular memory location and variable is just a name bound to it. In other words, type of variable depends on value assigned to it during run time. Python’s standard library has type() function to know the data type of variable. Following illustration shows how type of python variable changes dynamically.

>>> a=”Hello”  # variable a stores string object
>>> type(a)
<class 'str'>
>>> a=10 #variable a now stores integer number object
>>> type(a)
<class 'int'>
Published on 20-Dec-2017 08:47:54