What you'll learn
How to create a variable, update it, and use it inside text with f-strings.
Why it matters
Variables let a program remember a score, a username or the result of a calculation and use it again later.
Explanation
A variable is a name that points to a value. You create one with =:
age = 30Python works out the type for you; there is nothing else to declare. You can re-assign a variable any time.
Good names are lower-case with underscores: total_price, not TP. Names cannot start with a number or contain spaces.
To put variables inside text, use an f-string: put an f before the opening quote and wrap variables in curly braces.
name = "Asha"
print(f"Hello, {name}!")Example
name = "Asha"
price = 120
quantity = 3
total = price * quantity
print(f"{name} owes {total} rupees")
quantity = quantity + 1
total = price * quantity
print(f"Now {name} owes {total} rupees")Step-by-step walkthrough
- Three variables are created.
total = price * quantitycalculates 120 * 3 = 360 and stores it.- The f-string replaces
{name}and{total}with their values:Asha owes 360 rupees. quantity = quantity + 1makes it 4. The old total is not updated automatically, so we recalculate to get 480.- The last line prints
Now Asha owes 480 rupees.
Try it yourself
Add a discount = 20 variable and subtract it from the total before printing.
Common mistakes
- Using a name before assigning it, which gives a
NameError. - Forgetting the
fin front of an f-string; the braces are then printed literally. - Expecting a variable to update by itself. After
quantitychanges,totalis still the old number until you recalculate. - Names with spaces or dashes:
total priceandtotal-priceare invalid.
Quick quiz
Summary
name = valuecreates or updates a variable.- Use lower_case_with_underscores for names.
- f-strings put values into text.
Next: the different kinds of values.