Variables and Constants
Store, change, name, and swap values with variables and recognize constants by convention.
Store values in variables
A variable is a name that points to a value. Use the equals sign (=) to assign a value to a name.
Think of a variable as a labeled box: the label is the name and the value is what the box currently holds.
city = "Dhaka" print(city)
This assignment gives the name city the text value "Dhaka". Printing the variable shows its value.
Reassigning variables
Giving a variable a new value is called rebinding. The name now points to the new value instead of the old one.
level = 1 level = 2 print(level)
The first value is replaced when level = 2 runs. Python therefore prints 2.
Names and multiple assignment
Variable names can use letters, digits, and underscores, but they cannot start with a digit. Names are case-sensitive, so score and Score are different names. Use descriptive lowercase names with underscores, such as player_score.
first_name, age = "Asha", 12 left, right = "L", "R" left, right = right, left print(first_name, age) print(left, right)
Multiple assignment gives several names values at once. The swap works because Python evaluates the values on the right before assigning them to the names on the left.
MAX_LIVES = 3 pi_approximation = 3.14 print(MAX_LIVES) print(pi_approximation)
Python does not enforce true constants. By convention, an ALL_CAPS name such as MAX_LIVES tells readers that the value should not change. The values 3 and 3.14 written directly in code are called literals.
Key points
- Assignment uses = to give a variable a value.
- Rebinding gives an existing name a new value.
- Names cannot start with a digit.
- Multiple assignment can swap values.
- ALL_CAPS names signal constants by convention.
Worked example
Track a mobile wallet balance: start with 1000 taka, pay 250 for a train ticket, and see what remains.
balance = 1000 balance = balance - 250 print(balance)
How it works, step by step
- balance starts as 1000.
- The right side (balance - 250) is worked out first: 750.
- Then the result is stored back into balance — assignment always goes right to left.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetCreate variables first and second with values "sun" and "moon". Swap them, then print first followed by second.
# Write your code below
Check yourself
Variables and Constants quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.