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

 Live Demo

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.

Output

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 cane be assigned in single quotes or double quotes.

Example

 Live Demo

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

Output

2
<class 'str'>

Declare a float variable

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

We will use both.

Example

 Live Demo

x=2.0
print(x)
print(type(x))
y=float(2)
print(y)
print(type(y))

Output

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 variable 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.

Example

 Live Demo

x=10
print(x)
print(type(x))
x="abc"
print(x)
print(type(x))

Output

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.

Updated on: 23-Aug-2023

57K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements