Variables in Python

In this article, we discuss about variables, including how to use them to store and manipulate data, and the rules for naming and assigning values ​​to variables in Python.

Python, as a versatile programming language, provides powerful features to handle data. One such feature is variables, which allow programmers to store and manipulate data efficiently. In this article, we will explore the concept of variables in Python, understand their characteristics, and learn how to use them effectively. With practical examples, we will demonstrate the various aspects of variables and their significance in Python programming.

What are Python Variables?

Python variables are named containers used to store data values in memory. They allow programmers to assign values to a specific name and refer to that value throughout the program. Variables in Python are dynamically typed, meaning their type is inferred based on the assigned value.

Here are some examples of Python variables:

Example 1: Assigning values to variables

name = "Ali Nasiri"
age = 25
salary = 2500.50
is_employed = True

In this example, we assign different values to variables name, age, salary, and is_employed. The variable name stores a string value, age stores an integer value, salary stores a float value, and is_employed stores a Boolean value.

Example 2: Variable reassignment

x = 5
print(x)  # Output: 5

x = 10
print(x)  # Output: 10

In this example, we initially assign the value 5 to the variable x and print it. Then, we reassign the value 10 to x and print it again. The output shows that the variable x can be reassigned with a new value.

Example 3: Variable concatenation

first_name = "Ali Abdullah"
last_name = "Nasiri"
full_name = first_name + " " + last_name
print(full_name)  # Output: Ali Abdullah Nasiri

In this example, we concatenate two string variables first_name and last_name using the + operator. The result is stored in the full_name variable, which is then printed to display the concatenated full name.

These examples illustrate the concept and usage of Python variables. They demonstrate how variables can store different types of data, be reassigned with new values, concatenated, and have different scopes. Variables are an essential tool for data manipulation and storage in Python programming.

Understanding Memory Address

Data items belonging to different data types are stored in computer's memory. Computer's memory locations are having a number or address, internally represented in binary form. Data is also stored in binary form as the computer works on the principle of binary representation. In the following diagram, a string May and a number 18 is shown as stored in memory locations.

If you know the assembly language, you will covert these data items and the memory address, and give a machine language instruction. However, it is not easy for everybody. Language translator such as Python interpreter performs this type of conversion. It stores the 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 the data is stored in the memory, it should be accessed repeatedly for performing a certain process. Obviously, fetching the data from its ID is cumbersome. High level languages like Python make it possible to give a suitable alias or a label to refer to the memory location.

In the above example, let us label the location of May as month, and location in which 18 is stored as age. Python uses the assignment operator = to bind an object with the 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 same.

>>> id(month)
2167264641264
>>> id(age)
140714055169352

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

The id() function in Python:

In Python, the id() function is used to retrieve the unique identifier (memory address) of an object. It returns an integer that represents the memory address where the object is stored. Here are a few examples to illustrate the usage of the id() function:

Example 1: Retrieving the memory address of an integer object

x = 10
print(id(x))  # Output: 140731155315888

In this example, the id() function is used to retrieve the memory address of the integer object assigned to the variable x.

Example 2: Retrieving the memory address of a string object

name = "Ali Nasiri"
print(id(name))  # Output: 140731155420240

In this example, the id() function is used to retrieve the memory address of the string object assigned to the variable name.

Example 3: Comparing memory addresses of two objects python

x = 10
y = 10
print(id(x))  # Output: 140731155315888
print(id(y))  # Output: 140731155315888

In this example, the id() function is used to compare the memory addresses of two integer objects assigned to the variables x and y. Since both variables hold the same integer value, they refer to the same memory address.

In this example, the id() function is used to compare the memory addresses of two integer objects assigned to the variables x and y. Since both variables hold the same integer value, they refer to the same memory address.

Example 4: Retrieving the memory address of a list object

my_list = [1, 2, 3]
print(id(my_list))  # Output: 140731155121664

In this example, the id() function is used to retrieve the memory address of the list object assigned to the variable my_list.

The id() function can be useful when comparing or tracking the memory addresses of different objects. It is important to note that memory addresses can vary between different runs of the program or even within the same run, as Python's memory management system handles memory allocation and deal location dynamically.

Declaring Python Variables

In Python, there is no need to explicitly declare variables in order to reserve memory space or create them. When you assign a value to a variable, Python automatically creates it for you. The assignment operator = is used to assign values to variables.

The value on the right side of the = operator represents the data that will be stored in the variable, while the variable name on the left side of the = operator serves as a reference to that data. For instance:

# Creates an integer variable
name = "Ali Abdullah Nasiri"

# Creates an integer variable
age = 19

# Creates a floating point variable
score = 99.99

Printing Python Variables

After creating and assigning a value to a Python variable, we can use the print() function to display its value. The following example builds on the previous one and demonstrates how to print multiple variables in Python:

# Creates an integer variable
name = "Ali Abdullah Nasiri"

# Creates an integer variable
age = 19

# Creates a floating point variable
score = 99.99

print(name)
print(age)
print(score)

In this case, the variables name, age, and score are assigned the values Ali Abdullah Nasiri, 19, and 99.99, respectively. When executing the Python program mentioned above, the output will be as follows:

Ali Abdullah Nasiri
19
99.99

Deleting Python Variables

In Python, variables are used to store values and references to objects. At times, it may be necessary to delete a variable to free up memory or to reassign a different value. Python provides a way to delete variables 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 by using the del statement. For example:

del var
del var1, var2

It is important to note that deleting a variable does not delete the object it refers to, but only removes the reference to that object. If the object has no other references, it becomes eligible for garbage collection.

To better understand the concept, consider the following example:

x = 10
y = "Hello"
z = [1, 2, 3]

print(x, y, z)  # Output: 10 Hello [1, 2, 3]

del x

print(x, y, z)  # Output: NameError: name 'x' is not defined

In the above code, we create three variables x, y, and z, and assign them different values. After printing their values, we delete the variable x using the del statement. Trying to print the value of x after deletion results in a NameError, as the variable no longer exists.

In conclusion, the del statement in Python allows you to delete variables and remove references to objects. It is a powerful tool for managing memory and reassigning values in your Python programs.

Multiple Assignment of Python Variables

In Python, it is possible to initialize multiple variables in a single statement, allowing for more concise code. This feature becomes particularly useful when you want to assign the same value to multiple variables simultaneously. Consider the following example:

>>> a = 12
>>> b = 12
>>> c = 12

Instead of separate assignments, you can do it in a single assignment statement as follows:

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

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

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

These separate assignment statements can be combined in one. You need to give comma separated variable names on left, and comma separated values on the right of = operator.

>>> a, b, c = 12, 24, 36
>>> print (a, b, c)
12 24 36

Let's try few examples in script mode:

a = b = c = 500
print(a)
print(b)
print(c)

This produces the following result:

500
500
500

Here, an integer object is created with the value 500, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

name, age, score = "Ali Nasiri", 19, 100
print(name)
print(age)
print(score)

This produces the following result:

Ali Nasiri
19
100

Here, two integer objects with values 19 and 100 are assigned to variables age and score respectively, and one string object with the value Ali Nasiri is assigned to the variable name.

Naming Convention for Python Variables

Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. There are certain rules which should be taken care while naming a Python variable:

  • A variable name must start with a letter or the underscore character

  • A variable name cannot start with a number or any special character like $, (, * % etc.

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • Python variable names are case-sensitive which means Name and NAME are two different variables in Python.

  • Python reserved keywords cannot be used naming the variable.

If the name of variable contains multiple words, we should use these naming patterns:

  • Camel case: First letter is a lowercase, but first letter of each subsequent word is in uppercase. For example: kmPerHour, pricePerLitre

  • Pascal case: First letter of each word is in uppercase. For example: KmPerHour, PricePerLitre

  • Snake case: Use single underscore _ character to separate words. For example: km_per_hour, price_per_litre

Constants in Python

Python doesn't have any formally defined constants, However you can indicate a variable to be treated as a constant by using all-caps names with underscores. For example, the name PI_VALUE indicates that you don't want the variable redefined or changed in any way.

The naming convention for constants in Python typically involves using all capital letters and underscores to separate words. This helps to differentiate constants from variables and makes them easily identifiable.

Python vs C/C++ Variables

The way variables function in Python differs significantly from C/C++. In C/C++, a variable represents a named memory location. For instance, if we have variables a = 10 and b = 10, each of them will be stored in distinct memory locations. Let's assume their memory addresses are 100 and 200 respectively.

When a new value is assigned to the variable a - let's say 50, the previous value of 10 stored in the memory address 100 gets overwritten.

In Python, a variable is a reference to an object rather than a specific memory location. The object itself is stored in memory only once. Therefore, when we have multiple variables, they essentially serve as different labels for the same object.

When the statement a = 50 is executed in Python, a new integer object with the value of 50 is created in memory at a different location. This leaves the object 10, which is referred to by the variable b, unaffected. The two variables, a and b, now point to different memory locations and represent distinct objects.

Furthermore, if you assign a different value to the variable b, the object 10 remains unreferenced.

Python's garbage collector mechanism releases the memory occupied by any unreferred object.

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

>>> a = b = 10
>>> a is b
True
>>> id(a), id(b)
(140731955278920, 140731955278920)

Conclusion

In conclusion, this article has covered the fundamental concepts of variables in Python. We have explored their role in storing and manipulating data, as well as the rules and best practices for naming and assigning values to variables. By understanding these concepts, readers can effectively utilize variables to enhance their Python programming skills and develop efficient and readable code. With a solid grasp of variables, programmers can unlock the full potential of Python's flexibility and power in data manipulation and computation.

Last updated