Variables let a program store and reuse values. Assignments can create a name, update its binding, or use its current value in a new calculation.
Understanding the Concept
Python uses the = operator for assignments. A name becomes available after its assignment executes. You can update a numeric value by calculating a new one from the old value; for example, quantity = quantity + 2. Python does not require an explicit type declaration for ordinary variables. The name itself does not have to keep the same type, although stable and meaningful types make code easier to understand.
When and Why You Would Use This
Track an inventory quantity over two operations: a delivery increases stock and a sale decreases it. Separate variables for deliveries and sales make the calculation easy to audit.
Practical Example
stock_quantity = 10
delivery_quantity = 5
sold_quantity = 3
stock_quantity = stock_quantity + delivery_quantity
stock_quantity = stock_quantity - sold_quantity
print("Remaining stock:", stock_quantity)
Understanding the Example
The initial stock is 10, rises to 15, and falls to 12. Each assignment changes the binding of stock_quantity to a new integer result.
Example Output
Remaining stock: 12
Try It Yourself
Add a second delivery of 7 items and verify the final inventory value.
Common Beginner Mistakes
- Expecting assignment to update all related variables automatically.
- Using a variable before assigning it a value.
- Choosing names that do not describe quantities or units.
Key Takeaways
- Variables hold references to values used throughout a program.
- Assignments can rebind existing names.
- Break a sequence of updates into readable steps.