Python Variables
Python Variables

Python Variables

A variable is a reserved memory area (memory address) to store value.

Table of contents

Introduction

A variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python.

A variable can be either mutable or immutable. If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable.

Creating a variable

Due to flexibiltiy of python, it is needed to declare a variable before it can be used. The declaration happens automatically when we assign a value to the variable.  We can use the assignment operator = to assign a value to a variable. The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value.

name = "John"  # string assignment
age = 25  # integer assignment
salary = 25800.60  # float assignment

print(name)  # John
print(age)  # 25
print(salary)  # 25800.6

Changing the value of a variable

One advantage of variable in python is the ability to be able to use it dynamically unlike other programming language wherein the declare variable is static. A one data type can be assigned to a variable, and in the course of working, the same data can be assigned to another data types.

var = 10
print(var)  # 10

# print its type
print(type(var))  # <class 'int'>

# assign different integer value to var
var = 55
print(var)  # 55

# change var to string
var = "Now I'm a string"
print(var)  # Now I'm a string

# print its type
print(type(var))  # <class 'str'>

# change var to float
var = 35.69
print(var)  # 35.69
# print its type
print(type(var))  # <class 'float'>

Create Number, String, List variables

Python allows us to create these following 3 set of variables

  1. Numbers
  2. Strings
  3. List

Numbers Variable:

A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values.

  1. Int
  2. float
  3. complex
💡
Note: We used the built-in Python method type() to check the variable type.
  • Integer variable: The int is a data type that returns integer type values (signed integers); they are also called ints or integers. The integer value can be positive or negative without a decimal point.
# create integer variable
age = 28
print(age)  # 28
print(type(age))  # <class 'int'>
  • Float variable: Floats are the values with the decimal point dividing the integer and the fractional parts of the number.  Use float data type to store decimal values.
# create float variable
salary = 10800.55
print(salary)  # 10800.55
print(type(salary))  # <class 'float'>
  • Complex type: The complex is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values.
a = 3 + 5j
print(a)  # (3+5j)
print(type(a))  # <class 'complex'>

String Variable:

In Python, a string is a set of characters represented in quotation marks. Python allows us to define a string in either pair of single or double quotation marks. For example, to store a person’s name we can use a string type.

To retrieve a piece of string from a given string, we can use to slice operator [] or [:]. Slicing provides us the subset of a string with an index starting from index 0 to index end-1.

To concatenate the string, we can use the addition(+) operator.

# create a variable of type string
str = 'PYnative'

# prints complete string
print(str)  # PYnative

# prints first character of the string
print(str[0])  # P

# prints characters starting from 2nd to 5th
print(str[2:5])  # nat

# length of string
print(len(str))  # 8

# concatenate string
print(str + "TEST")  # PYnativeTEST

List types Variables

If we want to represent a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact. The list can be accessed in two ways, either positive or negative index.  The list has the following characteristics:

  1. In the list insertion order of elements is preserved.
  2. Heterogeneous (all types of data types intfloatstring) elements are allowed.
  3. Duplicates elements are permitted.
  4. The list is mutable(can change).
  5. Growable in nature means based on our requirement, we can increase or decrease the list’s size.
  6. List elements should be enclosed within square brackets [].
# create list
my_list = ['Jessa', 10, 20, 'Kelly', 50, 10.5]

# print entire list
print(my_list)  

Output
['Jessa', 10, 20, 'Kelly', 50, 10.5]

# Accessing 1st element of a list
print(my_list[0])  # 'Jessa'

# Accessing  last element of a
print(my_list[-1])  # 10.5

# access chunks of list data
print(my_list[1:3])  # [10, 20]

# Modifying first element of a list
my_list[0] = 'Emma'
print(my_list[0])  # 'Emma'

# add one more elements to list
my_list.append(100)
print(my_list)  # ['Emma', 10, 20, 'Kelly', 50, 10.5, 100]

Get the data type of variable

No matter what is stored in a variable (object), a variable can be any type like intfloatstrlisttupledict, etc. There is a built-in function called type() to get the data type of any variable.

The type() function has a simple and straightforward syntax.

type(<variable_name>)
a = 100
print(type(a))  # class 'int'

b = 100.568
print(type(b))  # class 'float'

str1 = "PYnative"
print(type(str1))  # class 'str'

my_list = [10, 20, 20.5, 100]
print(type(my_list))  # class 'list'

my_set = {'Emma', 'Jessa', 'Kelly'}
print(type(my_set))  # class 'set'

my_tuple = (5, 10, 15, 20, 25)
print(type(my_tuple))  # class 'tuple'

my_dict = {1: 'William', 2: 'John'}
print(type(my_dict))  # class 'dict'

Unlike what is stated above where the data types involve the <class ‘int’>, if we want to get the name only display, we can use the dot(.), and __name__

my_list =[10,20,20.5,'Python',100]

# It will print only datatype of variable
print(type(my_list).__name__) # list

Delete a variable

Use the del keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector.

Variable’s case-sensitive

Python is a case-sensitive language. If we define a variable with names a = 100 and A =200then, Python differentiates between a and A. These variables are treated as two different variables (or objects).

a = 100
A = 200

# value of a
print(a)  # 100

# Value of A
print(A)  # 200

a = a + A
print(a)  # 300

Constant

Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is not applicable. By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it.

MAX_VALUE = 500
💡
It is just convention, but we can change the value of MAX_VALUE variable.

Rules and naming convention for variables and constants

In Python, an identifier is a name used to identify a variable, function, class, module, or other object. It is a fundamental concept in programming, enabling the creation and reference of entities within a program. Here’s a detailed explanation of different types of identifiers in Python:

  • A variable name is an identifier used to reference a memory location where a value is stored. Variables allow you to store and manipulate data in a program.
  • A function name is an identifier used to define a function, which is a reusable block of code designed to perform a specific task.
  • A class name is an identifier used to define a class, which is a blueprint for creating objects. Classes encapsulate data for the object and methods to manipulate that data.
  • A module name is an identifier for a module, which is a file containing Python definitions and statements. Modules allow you to organize your code into manageable sections and reuse code across different programs.

There are some rules to define variables in Python. In Python, there are some conventions and rules to define variables and constants that should follow.

Rule 1: The name of the variable and constant should have a combination of letters, digits, and underscore symbols.

  • Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z)
  • Digits(0 to 9)
  • Underscore symbol (_)
total_addition
TOTAL_ADDITION
totalAddition
Totaladdition

Rule 2: The variable name and constant name should make sense.

Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful.

Example

x = "Jessa"  
student_name = "Jessa"

It above example variable x does not make more sense, but student_name is a meaningful variable.

Rule 3: Don’t’ use special symbols in a variable name

For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error

ca$h = 1000
ca$h = 11
      ^
SyntaxError: invalid syntax

Rule 4:  Variable and constant should not start with digit letters.

You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example.

1studnet = "Jessa"
print(1studnet)

Here Python will generate a syntax error at 1studnet. instead of this, you can declare a variable like studnet_1 = "Jessa"

Rule 5: Identifiers are case sensitive.

total = 120
Total = 130
TOTAL = 150
print(total)
print(Total)
print(TOTAL)

Output:

120
130
150

Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables totalTotalTOTAL.

Rule 6: To declare constant should use capital letters.

MIN_VALUE = 100
MAX_VALUE = 1000

Rule 6: Use an underscore symbol for separating the words in a variable name

If we want to declare variable and constant names having two words, use an underscore symbol for separating the words.

current_temperature = 24

Multiple assignments

We can do multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables.

  • Assigning a single value to multiple variables

we can assign a single value to multiple variables simultaneously using the assignment operator =. Now, let’s create an example to assign the single value 10 to all three variables ab, and c.

a = b = c = 10
print(a) # 10
print(b) # 10
print(c) # 10
  • Assigning multiple values to multiple variables
roll_no, marks, name = 10, 70, "Jessa"
print(roll_no, marks, name) 

# 10 20 Jessa

In the above example, two integer values 10 and 70 are assigned to variables roll_no and marks, respectively, and string literal, “Jessa,” is assigned to the variable name.

Variable Scope

Scope: The scope of a variable refers to the places where we can access a variable.

Depending on the scope, the variable can categorize into two types local variable and the global variable.

Local variable

A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error.

Global variable

A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.

Object/Variable identity and references

n Python, when we assign a value to a variable, we create an object and reference it.

For example, a=10, here, an object with the value  10 is created in memory, and reference anow points to the memory address where the object is stored.

Suppose we created a=10b=10, and  c=10, the value of the three variables is the same. Instead of creating three objects, Python creates only one object as 10 with references such as abc.

We can access the memory addresses of these variables using the id() method. ab refers to the same address in memory, and cde refers to the same address. See the following example for more details.

The id() function in Python returns the identity (memory address) of an object. This is useful for understanding how variables reference objects in memory. The value returned by id() is an integer that uniquely identifies an object during its lifetime.

Here's an example to illustrate how id() works:


# Example 1: Simple variable
a = 10
print("Value of a:", a)
print("Memory address of a:", id(a))

# Example 2: Multiple variables referencing the same object
b = 10
print("\nValue of b:", b)
print("Memory address of b:", id(b))

# Example 3: Changing the value of a variable
a = 20
print("\nNew value of a:", a)
print("New memory address of a:", id(a))

# Example 4: List object
my_list = [1, 2, 3]
print("\nValue of my_list:", my_list)
print("Memory address of my_list:", id(my_list))

# Example 5: Modifying the list
my_list.append(4)
print("\nModified my_list:", my_list)
print("Memory address of my_list after modification:", id(my_list))

Output:

Value of a: 10
Memory address of a: 4306141712

Value of b: 10
Memory address of b: 4306141712

New value of a: 20
New memory address of a: 4306142032

Value of my_list: [1, 2, 3]
Memory address of my_list: 4381917056

Modified my_list: [1, 2, 3, 4]
Memory address of my_list after modification: 4381917056

Explanation

  1. Simple Variable:
    1. pythonCopy code
      a = 10
      print("Value of a:", a)
      print("Memory address of a:", id(a))
      
      
    2. Here, a is assigned the value 10. The id(a) function returns the memory address of the integer 10.
  2. Multiple Variables Referencing the Same Object:
    1. pythonCopy code
      b = 10
      print("\nValue of b:", b)
      print("Memory address of b:", id(b))
      
      
    2. Since b is also assigned the value 10, it references the same object in memory as a (assuming a wasn't reassigned before this line). Thus, id(b) will return the same address as id(a).
  3. Changing the Value of a Variable:
    1. pythonCopy code
      a = 20
      print("\nNew value of a:", a)
      print("New memory address of a:", id(a))
      
      
    2. Now, a is reassigned the value 20. This points a to a new object in memory. Therefore, id(a) will return a different address than before.
  4. List Object:
    1. pythonCopy code
      my_list = [1, 2, 3]
      print("\nValue of my_list:", my_list)
      print("Memory address of my_list:", id(my_list))
      
      
    2. my_list is assigned a list object [1, 2, 3]. The id(my_list) function returns the memory address of this list object.
  5. Modifying the List:
    1. pythonCopy code
      my_list.append(4)
      print("\nModified my_list:", my_list)
      print("Memory address of my_list after modification:", id(my_list))
      
      
    2. The list is modified by appending 4. However, since lists are mutable objects, the memory address remains the same even after modification. Therefore, id(my_list) will return the same address as before.

This example shows how the id() function can be used to understand the memory addressing of objects in Python.

Unpack a collection into a variable

Packing

  • In Python, we can create a tuple (or list) by packing a group of variables.
  • Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing.
a = 10
b = 20
c = 20
d = 40
tuple1 = a, b, c, d # Packing tuple
print(tuple1) # (10, 20, 20, 40)

Tuple unpacking is the reverse operation of tuple packing. We can unpack tuple and assign tuple values to different variables.

tuple1 = (10, 20, 30, 40)
a, b, c, d = tuple1
print(a, b, c, d)  # 10 20 30 40

Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError.