Declare a variable in Python

Variables are the temporary placeholder for storing the value which has a unique name. In Python, you don’t need to declare the type of variable, this is done internally according to the value assigned.

Declare a variable in Python

Python supports following dataTypes –

  • Integer
  • Float
  • String
  • Boolean
  • etc.

Creating variable

Simply declare the variable name and assign a value to it using assignment operation (=).

Create variable in Python IDLE –

>>> a = 10
>>> b = 12.5
>>> name = "yogesh"
>>> c = True

Here, I defined variables in which a store integer value, b store decimal value, name store string value and c store boolean value.

You can print the value on the screen using the print() function.


>>> print(x)
>>> print(b)
>>> print(name)
>>> print(c)

Storing user input

The input() function is used to allow the users to input value and you can store it in a variable for later use within the program.
>>> num = input("Enter number : ")
Enter number : 43

You see an error on the screen when you directly try to perform arithmetic operations on the value returned by the input() function.


>>> num + 2
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in 
    num + 2
TypeError: Can't convert 'int' object to str implicitly

This is because in Python the input() function always returns the string object. When you perform concatenation between strings and integer object then its returns an error.

To avoid this convert the string object to an integer type using an int() function.


>>> num = int(input("Enter number : "))
>>> num + 2

Concatenate two string variable.

>>> text1 = "Hello"
>>> text2 = "World"
>>> text1 + " " + text2

Leave a Comment