Technical Roadmap

How to assign value to a variable in python

In this section, we will look at the various ways to Assign Values to variables in Python. While it seems as simple as using an equal sign, Python offers some powerful shortcuts that make your code much cleaner and more efficient than traditional languages.

The Assignment Operator (=)

In Python, the = sign is known as the Assignment Operator. It does not mean "equal to" (that is ==); instead, it tells Python to take the value on the right and store it in the name on the left.

The Logicoria Tip

Always remember: Right goes into Left. Python evaluates everything on the right side of the = first, and then gives that result to the variable name on the left.

Types of Assignment

Python provides three main ways to assign values, depending on how many variables you are dealing with:

Python
# Basic Assignment
age = 20

Multiple Assignment
name, age, course = "Arjun", 19, "BCA"

Chained Assignment
physics = chemistry = maths = 100

Augmented Assignment (Shortcuts)

Often in programming, you want to update a variable based on its current value (e.g., increasing a score). Python uses Augmented Assignment Operators to make this shorter:

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

Dynamic Re-assignment

Because Python is dynamically typed, a variable is not "locked" to a specific data type. You can assign a number to a variable and later assign a string to that same variable name without any errors.

Python
data = 100          # Currently an Integer
data = "Logicoria"  # Now it's a String!

Interview/Exam Tip

  • Swapping Variables: In most languages (like C++), you need a "temp" variable to swap two values. In Python, you can do it in one line: a, b = b, a.
  • Right-Side Evaluation: During multiple assignment, Python evaluates all expressions on the right before performing any assignments. This is why the one-line swap works!
The Logicoria Tip

Using x += 1 is preferred over x = x + 1. It's not just shorter to type; it's considered more "Pythonic" and cleaner to read for professional developers.