0
0
Pythonprogramming~5 mins

Assignment and augmented assignment in Python

Choose your learning style9 modes available
Introduction

Assignment lets you store values in a name (variable). Augmented assignment helps update that value quickly.

When you want to save a number or text to use later.
When you want to add or subtract from a value you already have.
When you want to multiply or divide a value and keep the result.
When you want to update a variable without writing it twice.
Syntax
Python
variable = value
variable += value
variable -= value
variable *= value
variable /= value

Use = to assign a value to a variable.

Use augmented assignment like += to update the variable by combining assignment and operation.

Examples
Assign 5 to variable x.
Python
x = 5
Add 3 to x and save the result back to x.
Python
x += 3
Subtract 2 from x and save the result back to x.
Python
x -= 2
Multiply x by 4 and save the result back to x.
Python
x *= 4
Sample Program

This program shows how to assign a value to x and then update it using augmented assignments step by step.

Python
x = 10
print(f"Start: x = {x}")
x += 5
print(f"After adding 5: x = {x}")
x -= 3
print(f"After subtracting 3: x = {x}")
x *= 2
print(f"After multiplying by 2: x = {x}")
x /= 4
print(f"After dividing by 4: x = {x}")
OutputSuccess
Important Notes

Augmented assignment is shorter and easier to read than writing variable = variable + value.

Augmented assignment works with many operators like +=, -=, *=, /=, and more.

When dividing with /=, the result becomes a float even if both numbers are integers.

Summary

Use = to store values in variables.

Use augmented assignment like += to update variables quickly.

Augmented assignment makes code shorter and clearer.