2.5 Assignment of Values to Variables (BT101CO)

Assigning values to variables is the process of storing data in a memory location and giving it a specific name for future reference. In Python, the = (equals sign) is used as the Assignment Operator.

It is important to remember that in an assignment statement, the right-hand side is evaluated first, and the resulting value is then "tagged" with the name on the left-hand side.

1. Basic Assignment

The most common way to assign a value is by using a single variable name and a single value.

  • Syntax: Variable_Name = Value
  • Example: age = 25

Here, age is the identifier (name) and 25 is the integer literal (value).

2. Multiple Assignment (Same Value)

Python allows you to assign the same value to multiple variables in a single line. This is useful for initializing several counters or flags to the same starting point.

  • Syntax: Var1 = Var2 = Var3 = Value
  • Example: x = y = z = 0

All three variables (x, y, and z) now point to the same memory object 0.

3. Multiple Assignment (Different Values)

You can also assign different values to multiple variables simultaneously in one line. This is often called Tuple Unpacking.

  • Syntax: Var1, Var2, Var3 = Val1, Val2, Val3
  • Example: name, roll_no, marks = "Ashok", 10, 85.5

"Ashok" is assigned to name, 10 to roll_no, and 85.5 to marks.

Note: The number of variables on the left must exactly match the number of values on the right.

4. Re-assignment

Because Python is dynamically typed, you can re-assign a variable to a completely different data type later in the program.

Example:

data = 100      # 'data' is an integer
data = "Python" # 'data' is now a string

The previous value (100) is orphaned in memory and eventually cleaned up by Python's garbage collector.

5. Augmented (Compound) Assignment

Python provides shorthand operators to perform a mathematical operation and an assignment in one step. These are common in loops and counters.

Operator Example Equivalent to
+= x += 5 x = x + 5
-= x -= 2 x = x - 2
*= x *= 3 x = x * 3
/= x /= 4 x = x / 4
%= x %= 2 x = x % 2

6. Dynamic Typing and Memory

When you assign a value, Python does the following:

  1. Creates an object in memory for the value (e.g., 5).
  2. Creates a variable (e.g., a).
  3. Links the variable to that object.

If you then say b = a, Python does not create a new 5. It simply links the variable b to the existing object 5 that a is already pointing to.

Practice Quiz