Variables
Give values names so your program can remember and reuse them.
Why it matters
Every AI program moves named values around. The prompt you send. The API key that proves who you are. The model's reply. The score you give that reply. Variables are how code holds on to those values from one step to the next. Get comfortable here, and the code in every later lesson reads like a list of plain instructions.
What you'll be able to do
- Store a value under a name and use it later
- Predict what a variable holds after it's reassigned
- Tell text, whole numbers and decimals apart with type()
- Pick names Python accepts and people can read
What it covers
- A name for a value
- Variables don't update themselves
- Types: what kind of value it is
- Naming variables
- Worked example: campaign metrics
- Why a variable isn't a spreadsheet cell
A name for a value
Think of a sticky label you put on a box. The label is the name, and whatever is in the box is the value. A variable is exactly that: a name that refers to a value. You create one with a single equals sign:
campaign = "Spring Sale" budget = 5000 print(campaign) print(budget)
Read budget = 5000 as "store 5000 under the name budget", not as "budget equals 5000". The = sign is an instruction, not a statement of fact. Python works out the value on the right first. Then it sticks the name on the left onto it.
Once a name exists, you can use it anywhere you'd use the value itself. That includes a calculation that creates another variable:
budget = 5000 spent = 1200 remaining = budget - spent print(remaining)
Step forward and watch the variables panel. When spent changes on line 5, remaining stays at 3800 until line 7 recalculates it.
Variables don't update themselves
That last example trips up almost everyone once. remaining = budget - spent does the subtraction at that moment, and stores the result: 3800. It does not set up a formula the way a spreadsheet cell does. Change spent afterwards, and remaining still holds 3800 until you run the calculation again.
For marketers: a spreadsheet cell like
=B2-C2recalculates whenever B2 or C2 changes. A Python variable is more like typing the result into the cell as a plain number.
Changing a variable
Giving a new value to a name that already exists replaces its old value. The right side is worked out first, so a variable can appear on both sides:
clicks = 120 clicks = clicks + 30 # take the current value, add 30, store the result print(clicks)
Adding to a variable is so common that Python has a shorthand: +=. The same works for the other operators too: -=, *= and /=.
clicks = 120 clicks += 30 clicks -= 10 print(clicks)
a = 10 b = a a = 20 print(b)
Show the answer
10
b = a stores the value a had at that moment, 10. Pointing a at 20 afterwards doesn't change b.
Types: what kind of value it is
Every value has a type, and the type decides what you can do with it. You can add two numbers, but you can't add a number to a sentence. The four types you'll meet first:
| Type | Name in Python | Examples |
|---|---|---|
| Text | str (string) | "Spring Sale", 'hello', "5000" |
| Whole number | int (integer) | 5000, -3, 0 |
| Decimal number | float | 0.035, 19.99, 5000.0 |
| True or false | bool (boolean) | True, False |
type() tells you a value's type:
print(type("Spring Sale")) print(type(5000)) print(type(0.035)) print(type(True))
Quotes make a string. "5000" is four characters of text that happen to be digits, so you can't do arithmetic with it. Python won't guess what you meant:
budget = "5000" print(budget + 100)
The error says Python can only join a string to another string. You'll see this a lot when data arrives from a file or an API as text. The next lesson, on numbers, shows how to convert between types with int(), float() and str().
Show the answer
str (text)
The quotes make it text, even though the characters look like a price. Without the quotes, 19.99 would be a float.
Naming variables
Python's rules for names:
- Letters, digits and underscores only. No spaces or hyphens.
- Can't start with a digit:
campaign2is fine,2campaignis not. - Case matters:
budgetandBudgetare two different names. - A few words are reserved because Python uses them, such as
if,for,classandTrue.
Nearly all Python code follows one style, called snake_case: lowercase words joined by underscores, like cost_per_click or email_open_rate. Choose names that say what the value is. ctr is fine in a short script about ads. x isn't: in three weeks, neither you nor an AI assistant reading your code will know what it holds.
A misspelled name gives a NameError, Python's way of saying it has never seen that name:
budget = 5000 print(Budget)
Read the last line of any error first. Here it names the exact thing Python couldn't find.
Worked example: campaign metrics
An email campaign went to 24,000 people. 1,920 clicked and 132 bought. Store the numbers, then work out the click-through rate (clicks ÷ sends) and the conversion rate (purchases ÷ clicks).
sends = 24000 clicks = 1920 purchases = 132 click_through_rate = clicks / sends conversion_rate = purchases / clicks print("CTR:", click_through_rate) print("Conversion rate:", conversion_rate)
Each raw number gets a clear name first, so the formulas read like the definitions you already know. Dividing two whole numbers with / gives a float: 0.08 is an 8% click-through rate. Change clicks and run it again. Both rates that depend on it change, because the formulas run again from the top.
Show the answer
open_rate = 0.21
Hyphens and spaces aren't allowed, names can't start with a digit, and snake_case (open_rate) is the Python convention.
Why a variable isn't a spreadsheet cell
In a spreadsheet, a cell can hold a formula, so it changes when its inputs change. A Python variable doesn't work like that. It holds the value that was worked out at the moment that line ran.
price = 10 total = price * 3 price = 20 print(total)
This prints 30, not 60. total was calculated when price was 10, and nothing tells it to look again. If you want a new total, run the calculation again after changing the price.
Two more traps
One equals sign isn't a question. In math class, = says two things are equal. In Python, a single = is an instruction: put this value under this name. You'll meet ==, which really does ask whether two things are equal, in the lesson on conditions.
Quotes make text. age = "42" stores the characters 4 and 2, not a number. Add 1 to it and Python stops with a TypeError, because it won't guess whether you meant arithmetic. When you see that error, check for stray quotes first.
Names can't contain spaces or hyphens. ad-spend looks like a name to you, but Python reads it as ad minus spend. Write ad_spend instead. Clear names are worth a few extra letters, since you'll read them far more often than you type them.
Practice what you just read
- 9 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 5 review cards for spaced repetition
Try a quiz question
What does this print?
print(type("5000"))