Python Variables
A variable is a name for a value. You create a variable by giving it a value with the equals sign, and from then on you can use the name wherever you need the value. Variables let a program remember things: a score, a name, a total that grows while the program runs.
Creating variables
In Python there is no separate step to declare a variable. The first time you assign a value, the variable exists:
name = "Asha"
age = 21
height = 1.62
print(name, "is", age, "years old and", height, "m tall.")Asha is 21 years old and 1.62 m tall.
The = sign does not mean "is equal to" as in mathematics. It means "take the value on the right and store it under the name on the left". That is why x = x + 1 makes sense in a program: it takes the old value of x, adds one and stores the result back in x.
Changing a value
A variable can get a new value at any time, and even a value of another kind. The old value is forgotten:
score = 0
print("Start:", score)
score = score + 10
score += 5 # the same as score = score + 5
print("Now:", score)
score = "finished"
print("Later:", score)Start: 0 Now: 15 Later: finished
Python remembers what kind of value a variable holds at each moment, but it does not fix the kind once and for all. This is called dynamic typing.
Naming rules
A variable name may contain letters, digits and the underscore _, but it cannot start with a digit and cannot be a keyword such as if or for. Names are case-sensitive, so total and Total are different. By convention Python programmers write names in lower case, with underscores between words: first_name, total_price, max_speed. Choose names that say what the value means; price is much clearer than p.
Several values at once
You can assign several variables in one line, which also gives Python's famous one-line swap:
x, y, z = 1, 2, 3
print(x, y, z)
a = b = 0
print(a, b)
first, second = "left", "right"
first, second = second, first
print(first, second)1 2 3 0 0 right left
Practice exercises
- Create variables for your name, your city and your year of birth, and print a sentence that uses all three.
- Start a variable
stepsat 0, add 1000 three times with+=and print the result. - Swap the values of two variables
aandbin one line and print them before and after. - Try to create a variable called
2nd_placeand read the error. Choose a valid name instead.