How to declare a variable in Python?

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.

Declare an Integer Variable

To declare an integer variable −

  • Name the variable

  • Assign an integer value to it

Example

x = 2
print(x)
print(type(x))

This is how you declare an integer variable in Python. Just name the variable and assign the required value to it. The datatype is automatically determined.

2
<class 'int'>

Declare a String Variable

Assign a string value to the variable and it will become a string variable. In Python, the string value can be assigned in single quotes or double quotes ?

Example

x = '2'
print(x)
print(type(x))
2
<class 'str'>

Declare a Float Variable

A float variable can be declared by assigning a float value. Another way is by typecasting ?

Example

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: String variables can also be declared using type casting when converting integer values to strings.

Dynamic Typing in Python

Unlike some other languages where you can assign only the value of the defined data type to a variable, Python variables are not bound to a particular datatype. Their datatype can be changed even after it is set ?

Example

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 a string value is assigned to it, it changes into a string variable.

Conclusion

Python uses dynamic typing where variables are created by assignment and their types are determined automatically. You can change a variable's type by assigning a different type of value to it.

Updated on: 2026-03-25T17:02:50+05:30

68K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements