🚀 Join our community of 100,000+ learners worldwide! 📚 2000+ free tutorials available 🎓 Get certified today! 💡 Learn at your own pace 🌟 New courses added weekly 🤝 Connect with expert instructors
Python - Variables - Ngahtech Tutorials

Python - Variables

0 min read Python – Application Areas / Python – Application Areas
Free Text

Python - Variables

Python Variables

Python variables are reserved memory locations used to store values within a Python program. This means that when you create a variable, you reserve some space in memory.

Based on the data type of a variable, memory space is allocated to it. Therefore, by assigning different data types to Python variables, you can store integers, decimals, or characters in these variables.

Memory Addresses

Data items belonging to different data types are stored in a computer's memory. Computer memory locations have a number or address, internally represented in binary form. Data is also stored in binary form because computers work on the principle of binary representation.

In the following example, a string "May" and a number 18 are shown as stored in memory locations.

If you know assembly language, you would convert these data items and memory addresses into machine language instructions. However, this is not easy for everyone. Language translators such as the Python interpreter perform this conversion automatically. Python stores an object in a randomly chosen memory location. Python's built-in id() function returns the address where the object is stored.

>>> "May"
May

>>> id("May")
2167264641264

>>> 18
18

>>> id(18)
140714055169352

Once data is stored in memory, it must be accessed repeatedly for performing certain operations. Fetching data directly from its memory ID is cumbersome. High-level languages like Python allow you to give a suitable alias or label to refer to the memory location.

In the above example, let us label the location of May as month and the location of 18 as age. Python uses the assignment operator (=) to bind an object with a label.

>>> month = "May"
>>> age = 18

The data object (May) and its name (month) have the same id(). The id() of 18 and age are also the same.

>>> id(month)
2167264641264

>>> id(age)
140714055169352

The label is an identifier. It is usually called a variable. A Python variable is a symbolic name that is a reference or pointer to an object.

Creating Python Variables

Python variables do not need explicit declaration to reserve memory space, or in other words, to create a variable. A Python variable is created automatically when you assign a value to it.

The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable, and the operand to the right is the value stored in the variable.

For example:

Example to Create Python Variables

This example creates different types (an integer, a float, and a string) of variables.

counter = 100          # Creates an integer variable
miles   = 1000.0       # Creates a floating point variable
name    = "Zara Ali"   # Creates a string variable

Printing Python Variables

Once we create a Python variable and assign a value to it, we can print it using the print() function.

Example to Print Python Variables

This example prints variables.

counter = 100          # Creates an integer variable
miles   = 1000.0       # Creates a floating point variable
name    = "Zara Ali"   # Creates a string variable

print(counter)
print(miles)
print(name)

Here, 100, 1000.0, and "Zara Ali" are the values assigned to counter, miles, and name variables, respectively.

When running the above Python program, this produces the following result:

100
1000.0
Zara Ali

Deleting Python Variables

You can delete the reference to a number object by using the del statement.

The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects using the del statement.

For example:

del var
del var_a, var_b

Example

The following example shows how we can delete a variable. If we try to use a deleted variable, then the Python interpreter throws an error.

counter = 100
print(counter)

del counter
print(counter)

This produces the following result:

100

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(counter)
NameError: name 'counter' is not defined

Getting Type of a Variable

You can get the data type of a Python variable using the built-in type() function.

Example: Printing Variable Types

x = "Zara"
y = 10
z = 10.10

print(type(x))
print(type(y))
print(type(z))

This produces the following result:

<class 'str'>
<class 'int'>
<class 'float'>

Casting Python Variables

You can specify the data type of a variable with the help of casting.

Example

This example demonstrates variable casting.

x = str(10)    # x will be '10'
y = int(10)    # y will be 10
z = float(10)  # z will be 10.0

print("x =", x)
print("y =", y)
print("z =", z)

This produces the following result:

x = 10
y = 10
z = 10.0

Case-Sensitivity of Python Variables

Python variables are case-sensitive, which means Age and age are two different variables.

age = 20
Age = 30

print("age =", age)
print("Age =", Age)

This produces the following result:

age = 20
Age = 30

Python Variables - Multiple Assignment

Python allows you to initialize more than one variable in a single statement.

In the following case, three variables have the same value.

>>> a = 10
>>> b = 10
>>> c = 10

Instead of separate assignments, you can write:

>>> a = b = c = 10
>>> print(a, b, c)
10 10 10

In the following case, we have three variables with different values.

>>> a = 10
>>> b = 20
>>> c = 30

These separate assignment statements can be combined into one.

>>> a, b, c = 10, 20, 30
>>> print(a, b, c)
10 20 30

Let's try a few examples in script mode.

a = b = c = 100

print(a)
print(b)
print(c)

This produces the following result:

100
100
100

Here, an integer object is created with the value 100, and all three variables are assigned to the same memory location.

You can also assign multiple objects to multiple variables.

a, b, c = 1, 2, "Zara Ali"

print(a)
print(b)
print(c)

This produces the following result:

1
2
Zara Ali

Here, two integer objects with values 1 and 2 are assigned to variables a and b, respectively, and one string object with the value "Zara Ali" is assigned to variable c.

Python Variables - Naming Convention

Every Python variable should have a unique name such as a, b, or c. A variable name can also be meaningful, such as color, age, or name.

The following rules should be followed when naming a Python variable:

  • A variable name must start with a letter or an underscore character.
  • A variable name cannot start with a number or any special character such as $, (, *, %, etc.
  • A variable name can contain only alphanumeric characters and underscores (A-Z, a-z, 0-9, and _).
  • Python variable names are case-sensitive, which means Name and NAME are different variables.
  • Python reserved keywords cannot be used as variable names.

If a variable name contains multiple words, the following naming patterns are recommended:

Camel Case

The first letter is lowercase, but the first letter of each subsequent word is uppercase.

Examples:

kmPerHour
pricePerLitre

Pascal Case

The first letter of each word is uppercase.

Examples:

KmPerHour
PricePerLitre

Snake Case

Words are separated using a single underscore (_).

Examples:

km_per_hour
price_per_litre

Example

The following are valid Python variable names:

counter = 100
_count = 100
name1 = "Zara"
name2 = "Nuha"
Age = 20
zara_salary = 100000

print(counter)
print(_count)
print(name1)
print(name2)
print(Age)
print(zara_salary)

This produces the following result:

100
100
Zara
Nuha
20
100000

Example

The following are invalid Python variable names:

1counter = 100
$_count = 100
zara-salary = 100000

print(1counter)
print($count)
print(zara-salary)

This produces the following result:

File "main.py", line 3
    1counter = 100
           ^
SyntaxError: invalid syntax

Example

Once you use a variable to identify a data object, it can be used repeatedly without referring to its id() value.

Here, we have variables width and height of a rectangle. We can compute the area and perimeter using these variables.

>>> width = 10
>>> height = 20

>>> area = width * height
>>> area
200

>>> perimeter = 2 * (width + height)
>>> perimeter
60

Using variables is especially advantageous when writing scripts or programs.

#!/usr/bin/python3

width = 10
height = 20

area = width * height
perimeter = 2 * (width + height)

print("Area =", area)
print("Perimeter =", perimeter)

Save the above script with a .py extension and execute it from the command line.

The result will be:

Area = 200
Perimeter = 60

Python Local Variables

Python local variables are defined inside a function. We cannot access them outside the function.

A Python function is a piece of reusable code.

Example

def sum(x, y):
    sum = x + y
    return sum

print(sum(5, 10))

This produces the following result:

15

Python Global Variables

Any variable created outside a function can be accessed within any function. Such variables have global scope.

Example

x = 5
y = 10

def sum():
    sum = x + y
    return sum

print(sum())

This produces the following result:

15

Constants in Python

Python does not have formally defined constants. However, you can indicate that a variable should be treated as a constant by using all-uppercase names with underscores.

For example:

PI_VALUE = 3.14159

The naming convention using all uppercase letters is sometimes referred to as screaming snake case, where the uppercase letters are the "screaming" part and the underscores represent the "snake".

Python vs C/C++ Variables

The concept of variables works differently in Python than in C/C++.

In C/C++, a variable is a named memory location. If:

a = 10;
b = 10;

then a and b occupy two different memory locations.

If a new value is assigned to a, such as 50, then the value 10 stored at that memory location is overwritten.

In Python, a variable refers to an object rather than a memory location. An object is stored in memory only once, and multiple variables can act as labels for the same object.

The statement:

a = 50

creates a new integer object 50 at a different memory location, while the object 10 is still referenced by b.

If b is later assigned a different value, the object 10 becomes unreferenced.

Python's garbage collector automatically releases memory occupied by unreferenced objects.

Python's identity operator is returns True if both operands have the same id() value.

>>> a = b = 10

>>> a is b
True

>>> id(a), id(b)
(140731955278920, 140731955278920)

This confirms that both variables reference the same object in memory.