Variables in Python | Declaration, Example

Variables in Python are nothing but the reserved memory locations to store values, such as numbers, some text string, objects, or anything.

Basically, a variable is a symbolic name given to a physical location in the computer’s memory and that memory location contains a value or data.

It tells the computer to store some data in the memory location or to retrieve that data from that memory location.

In simple words, whenever we create a variable in the Python program, we are allocating some space in the memory to store data values.

For example, in the below code, we are creating an integer variable and assigning a value to it.

num = 20 # an integer variable.

Here, num = 20 will store the value 20 in the computer’s memory location named num, as shown in the below figure. We have used an assignment operator (=) to assign a value to the variable.

Python variables

Memory Location of a Variable in Python


In the above code, 20 is an integer object stored in heap memory and “num” is a reference variable created in the main stack memory, containing the memory address of the integer object and is pointing to this integer object.

We can retrieve the memory address of integer object by using id() function. Look at the below example code.

num = 20
print(id(num))
Output:
      1449404138320

In the above example, the id() function generates a unique identification number for the integer object 20. This unique identification number is an integer value which will remain unique and constant for the Python object during its lifespan, as shown in the below figure. The id for integer object 20 is 1449404138320.

Memory location of a variable in Python

So, a variable is simply a reference to a value stored in the particular memory location. The size of memory reserved by the variable depends the type of value it is going to store. However, its value may vary during the time of execution, but at a time, only one value can be stored in it.

How to Declare Variables in Python?


A variable is a name of the location in the memory to hold some data or a value. We must give unique names for declaring variables to differentiate between different memory locations.

The rules for defining a variable name are the same as the defining identifiers in Python. Let’s understand some useful tips for defining a variable name.

a) Always choose a good name for defining a variable that will make your program easier to understand. For example, we can write a variable named st_rollNo for a student’s roll no, rather than srollno or sr.

b) Variable names should be as short as a single letter either in uppercase or lowercase.

c) Starts variable’s name with a letter of alphabet or an underscore (“_”).

d) Any letter or number can be used in the name after the first letter or underscore in the variable’s name.

e) Variable names should not start with a digit in Python. For example: 9Sept.

f) We cannot use blank space in between variable name. For example: Your roll no.

g) We cannot use special characters, such as -, /, #, or @, rather than underscore (“_”). For example, myname@ is invalid variable name because variable name contains special character.

h) Variable names are case-sensitive in Python. Therefore, uppercase (capitals) and lowercase letters are different. For example, “Score” and “score” are two different variables. They are not the same variables.

i) Don’t use reserved keywords or words Python uses as commands or library functions, such as “print”.

j) Variables can be of any length in Python.

Examples of some valid variable names:

  • employee
  • roll_no
  • average_score
  • sep9_Bday
  • _my_name
  • x
  • name_25
  • CollegeName
  • Length
  • _0_0_9
  • re_turn
  • none
  • x234

Examples of some invalid variable names:

  • 9Sep_Bday : invalid variable name because variable is starting with a digit.
  • Your age : invalid because variable cannot contain white space.
  • while : invalid because variable cannot be reserved keyword.
  • student@ : invalid because of having a special character.
  • sum of square
  • %_owed
  • raise%
  • global

Assigning Values to Variables in Python


One of the major difference between Python and other programming languages like C, C++, and Java is data types. In a strongly typed language, every variable must have a unique data type to reserve the memory space.

For example, the data type of variable is integer, the variable can hold only integer values during the execution of the program. Moreover, we must declare the variable first before using it in the program.

In the Python language, we do not need to declare the type of variable explicitly to reserve the memory space. The declaration happens automatically and internally according to the type of value when we assign a value to the variable.

Moreover, we do not need to declare a variable before using it in the Python program. We simply assign a value to a variable by using the assignment operator (=) and it exists in the memory.

The general syntax to create a variable with value in Python is as:

variable_name = value/expression

Here, the operand to the left of the = operator is the name of variable (i.e. an identifier) and the operand to the right of = operator is the literal value, expression with value, function, etc that we can store in a variable. We can store any type of value to a valid variable.

Basic Example Programs


Example 1:

Let’s create a Python program to create a variable and assign an integer value.

# Integer assignments.
x = 20 
y = 50
z = 100
# Print the values of variables on the console.
print(x)
print(y)
print(z)
Output:
      20
      50
      100

In the above program, we have assigned 20, 50, and 100 to the variables x, y, and z, respectively, and printed them on the console.


Example 2:

Let’s create a program where we will add marks of three subjects: physics, chemistry, and maths and print the marks obtained and percentage.

phy = 89
chem = 86
maths = 90
# Adding the marks of three subjects.
marks_obtained = phy + chem + maths

# Calculating the percentage.
per = (marks_obtained * 100) / 300
# Displaying the marks obtained and percentage.
print("Marks obtained in three subjects: ", marks_obtained)
print("Percentage: ", per)
Output:
      Marks obtained in three subjects: 265
      Percentage:  88.33333333333333

Example 3:

Let’s take another example program where we will initialize different values to different variables.

x = 80 # an integer assignment.
y = 99.99 # a floating point assignment.
name = 'Radhika' # a string assignment.
print(x); print(y); print(name);
Output:
      80
      99.99
      Radhika

Here, we have assigned 80, 99.99, and ‘Radhika’ values to the variables x, y, and name, respectively, and printed the values of the above variables on the console.


Example 4:

Let’s create a Python program to find the perimeter and area of a circle having the radius 5 cm. The formulas for finding the perimeter and area of a circle are 2πr and πr², respectively, where π = 3.14.

radius = 5
pi = 3.14
perimeter = 2 * pi * radius
area = 3.14 * radius * radius
print("Perimeter of the circle = ", perimeter)
print("Area of the circle = ", area)
Output:
      Perimeter of the circle =  31.400000000000002
      Area of the circle =  78.5

Here, we have created four variables as:

  • The variable radius that stores the value of the length of radius.
  • The variable pi stores the value 3.14.
  • And other perimeter and area that stores the value of the perimeter and area of the circle, respectively.
  • At last, we have displayed the perimeter and area of the circle.

In Python, one more important point is that not only the value of a variable, but the type of a variable can change as well during the execution of the program.

Python is a dynamic-typed language. It does not know about the type of variable until we execute the program code. Let’s see the example code below.

Example 5:

# Assigning the new value to the same variable.
x = 10 # an integer variable.
x = 'text' # a string variable.
print(x)
x = 25.50 # a float variable.
print(x)
x = True # a boolean variable.
print(x)
Output:
      text
      25.5
      True

Multiple Assignment


Python allows us assigning a common value to multiple variables in a single line followed by an assignment operator, which is known as multiple assignment. We can apply multiple assignment in two ways:

a) By assigning a single value to multiple variables:

x = y = z = 20
print(id(x))
print(id(y))
print(id(z))
Output:
      1789601907536
      1789601907536
      1789601907536

Here, we have created an integer object with a value of 20 and assigned it to all three variables. We can see in the output all three variables pertain to the same memory location 1789601907536.

This means that all three reference variables x, y, and z are pointing to the same object 20. Python interpreter does not create another object for it.

We can also write the above code like this:

x = 20
y = x
z = y
print(id(x))
print(id(y))
print(id(z))
Output:
      2170578600784
      2170578600784
      2170578600784

b) Assigning multiple values to multiple variables:

We can also assign multiple values or objects (whether they are the same or different) to multiple variables in a single line. While assigning, the left and right must have the same number of elements. Let’s see the following example code.

x, y, z = 20, 25.50, 'text'
print(id(x))
print(id(y))
print(id(z))
Output:
      2125019808592
      2125020848336
      2125020269488

In the above example, we have assigned an integer object with value 20, and a float object with a value 25.50 to variables x, and y respectively. The string object “text” is assigned to the variable z.

Now, you can observe in the output all three variables pertain different memory locations. This means that all three variable are pointing to different objects in different memory locations.


Let’s take one more example in which we will assign multiple values to multiple variables in a single line and print their values one by one.

fruit1, fruit2, fruit3 = "Banana", "Orange", "Mango"
print(fruit1)
print(fruit2)
print(fruit3)
Output:
      Banana
      Orange
      Mango

How to determine the data type of Variables in Python?


To know the data type of a variable, use type() function. The general syntax to know the type of a variable is as:

type(variable_name)

Let’s take an example based on determining the type of variable.

num = 100
print(type(num))
Output:
      <class 'int'>

Here, we are storing an integer object 100 in variable num, the Python interpreter assumes int as the type of variable. Therefore, the outcome is <class ‘int’>, meaning that the variable num is an object of the int class.


Let’s see another program where we will assign float value to the variable num and see the type of variable.

num = 100.990
print(type(num))
Output:
      <class 'float'>

In this tutorial, we have elaborated on Python variables with various example programs. Hope that you will have understood the basic definition of variable, related concepts, and practiced all programs.
Thanks for reading!!!
Next ⇒ Data Types in Python⇐ Prev Next ⇒

Please share your love