In Python, we need not declare a variable with some specific data type.
Python has no command for declaring a variable. A variable is created when some value is assigned to it. The value assigned to a variable determines the data type of that variable.
Thus, declaring a variable in Python is very simple.
Just name the variable
Assign the required value to it
The data type of the variable will be automatically determined from the value assigned, we need not define it explicitly.
To declare an integer variable −
Name the variable
Assign an integer value to it
x=2 print(x) print(type(x))
This is how you declare a integer variable in Python. Just name the variable and assign the required value to it. The datatype is automatically determined.
2 <class 'int'>
Assign a string value to the variable and it will become a string variable. In Python, the string value cane be assigned in single quotes or double quotes.
x='2' print(x) print(type(x))
2 <class 'str'>
A float variable can be declared by assigning float value. Another way is by typecasting.
We will use both.
x=2.0 print(x) print(type(x)) y=float(2) print(y) print(type(y))
2.0 <class 'float'> 2.0 <class 'float'>
Note: The string variable can also be declared using type casting, when using integer values as string.
Unlike some another languages, where we can assign only the value of the defined data type to a variable. This means an integer varibale can only be assigned an integer value throughout the program. But,in Python , the variable are not of a particular datatype. Their datatype can be changed even after it is set.
The following example will clarify the above concept.
x=10 print(x) print(type(x)) x="abc" print(x) print(type(x))
10 <class 'int'> abc <class 'str'>
The variable x was of type int. Later when string value is assigned to it, it changes into a string variable.