Variables
Programming Languages · Python Basics · 8 min
Store values in named boxes, change them, and print them.
Store a value
A variable is a name for a value, like a label on a box. The = sign puts the value on the right into the name on the left.
color = "blue"
print(color)
Notice: no quotes around color inside print(). That tells Python to look up the variable, not print the word.
Create a variable
cityand set it to"Paris".Print
city.
Variables can change
It's called a variable because it can vary. Give it a new value with = again and the old one is replaced.
lives = 3
lives = 2
print(lives) # 2
You can even use the old value to make the new one: lives = lives - 1.
Below the first print, change
scoreto15.Print
scoreagain.
Naming rules
Variable names can use letters, numbers and underscores _. They can't start with a number or contain spaces. Python also cares about capitals: Age and age are two different variables.
When a name has several words, Python programmers join them with underscores. This is called snake_case:
high_score = 99
Create
first_nameandfavorite_food, each holding some text.Print both variables.
Variables inside print
print() can show several things at once. Separate them with commas and Python puts a space between each one:
item = "apple"
count = 3
print("I have", count, item)
That prints I have 3 apple. You can mix text, variables and maths in the same print().
Print
Ada is 36using the variablesnameandage.Print
Next year: 37usingage + 1.
Put it together: a pet profile
Let's describe a pet, then give it a birthday. Use variables for everything, so the birthday only needs one small change.
Create
pet_nameset to"Rex"andpet_ageset to3.Print
Rex is 3using the two variables.Birthday! Add 1 to
pet_age, then print the same line again.
More in Python Basics
Previous: Hello, World! · Next: Numbers and Maths