Variables in Python

Haider Ali
Python Tutorial [Beginner to Advance]
2 min readApr 1, 2024

Lesson#7

What is a variable?

Variable is a named memory location where data can be stored. They can also be defined as containers for storing data.

Unlike strongly typed programming languages there is no need to declare a variable before using it. A variable is created when it is assigned value for the fist time in Python.

Example:

x = 10
y = "Apple"
print(x)
print(y)

In the given example x and y are two variables with integer and String data type respectively.

Data type of the variable is determined by the value it is assigned. In our example x is integer becuase integer value has been assigned. y is String becuase string value has been assigned.

Type of a variable may change inside the program when different type of value is assigned.

x = 100
x = "New York"
print(x)

The program will run without any errors and print “New York” on the screen.

In this example data type of variable x was changed from int to str when the value of “New York” was assigned to it.

Variable names

Variable name in Python can be short or long but it should following the following rules:

It must start with a letter or the underscore character

It can only contain alpha-numeric characters (A-z, 0–9) and underscores ( _ )

It cannot start with a number

It cannot be any of the Python keywords.

Variable names are case sensitive and a variable ‘a’ is different from ‘A’.

Examples of valid variable names are:

x = 10
xyz =100
abc_123 ="Pakistan"
abc_123_xyz = "Another variable

Examples of invalid variable names are:

1a = 10
my-var = "Cat"
var# = "Dog"

--

--