Python Variables

In Python programming, a variable is a reserved memory location for storing data values. Unlike other languages, Python does not have any keyword to declare a variable.

Different data types in Python are Numbers, Strings, List, Tuple, Set, Dictionary etc. Python variables do not need to be declared with any particular data type and can even change their type after they have been initialized. 

The following example shows this: 

# Variable Test 1
x = 25 # integer value
print("x =", x)
x = "India" # string value
print("x =", x)
x = 52.7 # floating-point value
print("x =", x)

Output:

x = 25
x = India
x = 52.7

 

Rules for Python variables

Rules for Python variables are as follows:

  • A variable name must start with a letter or underscore (_)
  • A variable name can’t start with a number
  • A variable name can only contain alpha-numeric characters and underscore character (A-z, 0-9, and _ )
  • Variable names are case-sensitive in Python (year, Year and YEAR are three different variables)

To combine both text and a variable, Python uses the ‘+‘ character. For numbers, the character ‘+‘ works as a mathematical operator. See the example below: 

# Variable Test 2
x = "Great"
print("Python is " + x)
x = 15
y = 10
print(x + y)

Output:

Python is Great
25

 

Multiple variables together

Python allows for assigning values to multiple variables in one line. And it can also assign the same value to multiple variables in one line. See the code below:

# Variable Test 3
a, b, c, d = "Delhi", "Kolkata", "Mumbai", "Chennai"
print(a, b, c, d)
a = b = c = d = "India"
print(a, b, c, d)

Output:

Delhi Kolkata Mumbai Chennai
India India India India