Variables
In this tutorial, we'll store values with clear names and reuse them in code.
A variable is a name that points to a value. You use variables when you want to store information and reuse it later.
name = "Aisha"
age = 12
print(name)
print(age)
Here, name points to the string "Aisha", and age points to the integer 12.
Why Variables Are Useful
Without variables, you repeat values everywhere:
print("Maya scored 8")
print("Maya needs 2 more points")
With variables, the code becomes easier to change:
student = "Maya"
score = 8
points_needed = 10 - score
print(student, "scored", score)
print(student, "needs", points_needed, "more points")
If the score changes, you only change one line.
Naming Variables
Good variable names describe what the value means:
temperature = 21
first_name = "Ben"
is_logged_in = False
Poor names make code harder to read:
x = 21
a = "Ben"
b = False
Short names are fine for tiny examples, but real programs are easier when names are clear.
Reassigning Variables
Variables can point to a new value later:
score = 0
print(score)
score = 10
print(score)
Python runs from top to bottom, so the second assignment replaces the first one.
You can also update a variable using its current value:
score = 10
score = score + 5
print(score)
This means: take the old value of score, add 5, and store the result back in score.
Common Mistakes
Variable names cannot contain spaces:
first name = "Ada" # wrong
Use underscores instead:
first_name = "Ada"
Variable names are case-sensitive. score, Score, and SCORE are three different names.
Practice
Create variables for a product name, price, and quantity. Print a sentence that includes all three values.