Python Variables
Python · Variables & Data Types
Theory
A variable in Python is a name that refers to an object in memory. When you write sales = 250, Python first evaluates the right side, creating an int object holding 250, and then binds the name sales to that object. There is no declaration step and no type attached to the name; the variable exists from the moment it is first assigned, and using it before that raises NameError.
Think of a variable as a label tied to a box, not the box itself. Assigning b = a ties a second label to the same object, it does not copy anything. For immutable values like numbers and strings this never surprises you, because changing b really means re-pointing b at a new object. For mutable objects like lists, both names see every change made through either one. Reassigning sales = 'high' later is allowed; the name simply points at a different object of a different type.
Why we use it
Variables let you store a value once and reuse it by name, so calculations are readable (total = price * quantity) and easy to change. Understanding names-as-references explains many beginner surprises with lists and dictionaries.
When to use it
Create a variable whenever a value is used more than once or deserves a meaningful name. If you need an independent copy of a list or dict, do not just assign it to a new name; use .copy() or list(old) so changes do not leak between them.
How it works
- Python meets sales = 250
- Evaluate the right-hand side first: create the int object 250
- Does the name sales already exist? Yes: Re-point it at the new object. No: Create the name in the current scope.
- Bind the name to the object
- Later, print(sales) looks the name up and fetches its object
- Output: 250
Syntax
variable_name = valueExample
sales = 250
city = "Mumbai"Key points
- No need to declare a type explicitly
- Names are case-sensitive: sales and Sales are different
- A variable is a reference to an object, not the object itself
- b = a makes both names point to the same object; it does not copy
- Using a name before assigning it raises NameError
- Swap two values in one line: a, b = b, a