Variables in Python
Topic 2 of 58 · 7 minFree lessonA variable is a name for a value. Think of a box with a label on it. The label is the name, and the thing inside is the value.
Variables let your program remember things, like a player's score or a user's name. You can use the value again and again just by writing the name.
Making a variable
Write a name, then =, then the value. Python stores the value under that name.
name = "Ada"age = 36print(name)print(age)In Python, = means "store this value". It does not mean "equals" like in math class. Read age = 36 as "age gets 36".
Changing a value
You can put a new value in the box at any time. Python keeps only the latest one.
score = 10score = 15print(score)Using variables together
Variables can be used to make new values. Here * means multiply. You'll see all the math signs in the next topic.
price = 4quantity = 3total = price * quantityprint(total)To print a label and a value together, separate them with a comma. Python adds a space between them.
city = "Lisbon"print("I live in", city)Naming rules
Variable names follow a few rules:
- Use letters, numbers and underscores
_only. - Don't start with a number.
score1works, but1scoredoes not. - No spaces. Use an underscore instead, like
first_name. - Capital letters matter.
Scoreandscoreare two different variables.
print(points)points = 5Create the variable first, then use it.
total_price is much easier to understand than tp or x.Try it yourself
Run the code in the editor and answer 8 practice questions on variables. It's free, you only need an account.