Variables
Overview
A variable stores a value under a name so you can use it later. Variables are how programs remember things: a score, a user’s name, a running total. They’re the first building block of every program.
Creating variables
name = "Asha"
age = 29
height = 1.68
is_member = TrueThe = sign is assignment, not “equals” in the maths sense. It means: take the value on the right and attach the name on the left to it. Then you use the name instead of the value:
print(name, "is", age) # Asha is 29
print("Next year:", age + 1) # Next year: 30Names are attached to values
It helps to picture variables correctly from the start. A Python variable isn’t a box that holds a value; it’s a label attached to a value:
score = 42
total = score # total now refers to the same 42For numbers and text this distinction rarely matters, because they can’t be changed in place. It becomes important with lists (Lists), where two names attached to the same list both see changes to it.
Reassigning
Assign again and the name moves to the new value:
mood = "tired"
mood = "happy"
print(mood) # happyThe right-hand side is evaluated first, so a variable can use its own old value:
score = 10
score = score + 5 # 15Augmented assignment
That pattern is so common there’s a shortcut:
score += 5 # score = score + 5
lives -= 1 # lives = lives - 1
price *= 1.2 # price = price * 1.2
total /= 2 # total = total / 2Naming rules and style
Rules (Python enforces them):
- letters, digits and underscores only:
total_price,item2; - can’t start with a digit:
2nd_placeis an error; - case-sensitive:
scoreandScoreare different; - can’t be a keyword —
if,for,class,True,def,returnand the other words Python reserves.
Style (the Python convention, from the style guide PEP 8):
- snake_case: lowercase words joined by underscores —
hotel_per_night, nothotelPerNight; - descriptive:
nightsnotn,food_per_daynotfpd. Short names are fine for tiny loops (i) and well-known maths (x,y); - UPPER_CASE for constants that shouldn’t change:
VAT_RATE = 0.2.
Avoid reusing names of built-in functions such as list, str, sum or print — sum = 10 works, but then the sum() function is hidden for the rest of your program.
Several at once
x, y, z = 1, 2, 3 # assign several names
a = b = 0 # the same value to several names
a, b = b, a # swap two variablesThe swap works because Python evaluates the whole right-hand side (b, a) first, then assigns.
Dynamic typing
Every value has a type — int for whole numbers, float for decimals, str for text, bool for True/False. You don’t declare types; Python works them out:
>>> type(29)
<class 'int'>
>>> type("Asha")
<class 'str'>
>>> type(1.68)
<class 'float'>A variable can even be reassigned to a value of a different type. Python allows it, but doing it on purpose usually makes code confusing — keep each variable to one kind of value.
Using a variable before creating it
print(total)NameError: name 'total' is not definedA variable exists only after its assignment has run. Check for typos and make sure the assignment comes first.
Good names are half of readable code. If you have to add a comment to explain what a variable holds, try renaming it instead.
A trip budget
Write a program for a weekend trip. Create variables for the cost of the train ticket (45), the hotel per night (80), the number of nights (2) and a daily food budget (30). Calculate the total cost of the trip (food is per day, and the trip lasts one day longer than the number of nights). Then the hotel announces a 10 USD discount per night — update the hotel price using an augmented assignment and recalculate. Print both totals with labels, and finally swap two variables a and b in one line.
# 1. Variables for the trip
# 2. Total cost (days = nights + 1)
# 3. Hotel discount of 10 per night, recalculate
# 4. Swap a and b in one line
a = "left"
b = "right"# 1. Variables for the trip
train_ticket = 45
hotel_per_night = 80
nights = 2
food_per_day = 30
# 2. Total cost (days = nights + 1)
days = nights + 1
total = train_ticket + hotel_per_night * nights + food_per_day * days
print("Trip total:", total) # 45 + 160 + 90 = 295
# 3. Hotel discount of 10 per night, recalculate
hotel_per_night -= 10
total = train_ticket + hotel_per_night * nights + food_per_day * days
print("With discount:", total) # 275
# 4. Swap a and b in one line
a = "left"
b = "right"
a, b = b, a
print(a, b) # right leftSummary
name = valuecreates a variable — a name attached to a value — and reassigning moves the name to a new value.- Use descriptive snake_case names: letters, digits and underscores, not starting with a digit.
- Augmented assignment updates a variable:
score += 10meansscore = score + 10. - Several names can refer to the same value;
a, b = b, aswaps two variables. - Python is dynamically typed: a variable can hold any type, and
type(x)tells you which.