…
…
Python Programming Fundamentals · Lesson 2 / 40 · Variables
PreviewIn this lesson you will
= and +=, and then recalculate the resultYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the Corner Café register program, the latte price, 4.25, is typed by hand into every line that needs it. When Ada raises the latte by 50 cents, she has to find and change every line that contains 4.25, and if she misses one, the receipt comes out wrong. In this lesson we will move the prices and the register into places that have names, that is, into variables.
First, let's look at the problem up close. With the print you learned in the last lesson, Ada's program looks like this today:
print("Latte:", 4.25) print("Cookie:", 2.00) print("2 lattes:", 4.25 * 2) print("Latte + cookie:", 4.25 + 2.00) print("2 lattes + 1 cookie:", 4.25 * 2 + 2.00) print("3 lattes:", 4.25 * 3)
OutputLatte: 4.25
Cookie: 2.0
2 lattes: 8.5
Latte + cookie: 6.25
2 lattes + 1 cookie: 10.5
3 lattes: 12.75The program works, but the number 4.25 appears in five different places. When the latte goes up, you have to fix all five places one by one. If you skip one, the program does not raise an error; it quietly gives the wrong result, which is the most dangerous kind of mistake. And think about this: how would someone who sees 4.25 know whether it is the price of a latte or a table number? The program you write by the end of this lesson will keep the price in a single place and will change only that place when the price goes up. Our target output is this:
OutputTotal: 10.5
Total after the price increase: 11.5While a program runs, it needs to keep information somewhere: how much is a latte, how many cookies are in the basket, how much money has built up in the register? In Python, we keep this information in variables. A variable is a name we give to a value. You name the value once, and then everywhere in the program you use the name instead of the number itself.
To create a variable, you write the name first, then the = sign, and the value last: latte = 4.25. Do not read this line as "latte equals 4.25"; read it as "put 4.25 into the box called latte". The = here is not the equals sign from math; in Python it is the assignment sign. Python always handles an assignment line in the same order: it first calculates the right side, and then ties the result to the name on the left. That is why the name always stands on the left and the value always on the right.
Writing a name with quotes or without quotes are two very different things. String inside quotes, as you know from the last lesson, is a string that appears on the screen as it is. A name without quotes tells Python "find the box with this name and bring what is inside". Let's print the same word in both ways:
latte = 4.25 print("latte") print(latte) print("Latte:", latte)
Outputlatte
4.25
Latte: 4.25The first print printed the word inside quotes exactly as written. The second saw the name latte without quotes, looked at the box, and brought 4.25. The third put the two side by side with a comma: first the label string, then the value in the box. You will use this third pattern most on receipts.
After you create a variable, you can use its name anywhere the value would be written. You can also combine variables in a calculation. The receipt Ada writes most often is two lattes and one cookie:
latte = 4.25 cookie = 2.00 total = latte * 2 + cookie print("Total:", total)
OutputTotal: 10.5Pay attention to what happens on the third line. Python does not create the total box right away. First it looks at the expression on the right, latte * 2 + cookie, takes 4.25 from the latte box and 2.0 from the cookie box, calculates 4.25 × 2 + 2.0 = 10.5, and only after that puts 10.5 into the total box. On the last line, when print sees the name total, it prints the 10.5 in the box. In the block below, run the code line by line and watch which box appears at each step.
Run the code line by line: see which line runs next, the variable boxes and the output.
latte = 4.25 cookie = 2.00 total = latte * 2 + cookie print("Total:", total)
Here is the real benefit of variables. When a price changes, you do not touch the calculation line at all; you only change the value in the first lines. Below, choose different prices for the latte and the cookie. See how the output changes while the calculation line stays the same.
Change the latte and cookie prices: how does the total change without touching the calculation line?
Pick a value; predict the output first, then look.
1latte = 4.252cookie = 2.003total = latte * 2 + cookie4print("Total:", total)
Total: 10.5
Faded lines didn't run with this value. The only things you changed are the values in the first two lines. The line total = latte * 2 + cookie uses the current values in the boxes every time; that is how Ada's trouble of fixing five lines one by one comes to an end.
The point where beginners get stuck most often is the direction of the = sign. In math, x = 5 and 5 = x say the same thing; in Python they do not. If you write 4.25 = latte, Python says "there is no box called 4.25, I cannot put a value into a number" and raises the error SyntaxError: cannot assign to literal here. The rule is simple: the name of the box on the left, the value to put into it on the right.
This is where the word "variable" comes from: its value can change while the program runs. When you assign a new value to the same name, the old value in the box comes out and the new one goes in. If Ada raises the latte by 50 cents, you can write this:
latte = latte + 0.50
From a math point of view, this line looks silly; no number is equal to itself plus 0.50. But you read it as an assignment, from right to left: first the right side is calculated, the 4.25 in the box is taken and 0.50 is added (4.75), and then the result is put back into the latte box. The old 4.25 is no longer called by this name. This is done so often that Python has a short way to write it: latte += 0.50. The same family works for subtraction and multiplication too: latte -= 0.25 takes 25 cents off, and quantity *= 3 triples the quantity.
| Line | Right side (calculated first) | latte is now |
|---|---|---|
latte = 4.25 | 4.25 | 4.25 |
latte = latte + 0.50 | 4.25 + 0.50 | 4.75 |
latte += 0.50 | 4.75 + 0.50 | 5.25 |
latte -= 0.25 | 5.25 - 0.25 | 5.0 |
Now the most important idea of the lesson. Updating a variable does not automatically update results that were calculated with that variable earlier. In a spreadsheet, when you change the price cell, the total cell changes too; Python does not work like that. At the moment the line total = latte * 2 + 2.00 runs, a number is calculated and that number is put into the box. A formula is not put into the box; a result is.
latte = 4.25 total = latte * 2 + 2.00 latte += 0.50 print(total) total = latte * 2 + 2.00 print(total)
Output10.5
11.5The first print prints 10.5, because total was calculated while the latte was still 4.25. The price increase changed the latte box and did not touch the total box. To see the correct total, the calculation line had to run again; only then did the second print print 11.5. Follow the same situation in the block below: when price becomes 3.25, does the value in the total box change?
Run the code line by line: see which line runs next, the variable boxes and the output.
price = 3 quantity = 2 total = price * quantity price = 3.25 print(total) print(price)
total stayed at 6 and price became 3.25. The total does not update by itself; it updates only when the calculation line runs again. The same rule holds when you assign a variable to another variable. The line old = latte does not tie the two names together; into the old box goes a copy of whatever is in the latte box at that moment.
Before the price increase, Ada writes the old price aside. What does this code print?
latte = 4.25
old = latte
latte = 4.75
print(old)Now you have all the parts of the target program. The prices are in variables, the price increase is on a single line, and the total is recalculated after the increase. We named the steps with comments; in the exercises you will build the same steps yourself.
# 1. Write the prices into variables latte = 4.25 cookie = 2.00 # 2. Calculate the total and print it total = latte * 2 + cookie print("Total:", total) # 3. Raise the price, recalculate the total latte += 0.50 total = latte * 2 + cookie print("Total after the price increase:", total)
OutputTotal: 10.5
Total after the price increase: 11.5You cannot give a variable any name you like; Python has a few firm rules. If you write a name that breaks the rules, the program does not run at all.
_); it cannot start with a digit. latte2 works, 2latte does not.latte price looks to Python like two separate names. No hyphens either: when you write latte-price, Python reads it as "latte minus price".Latte and latte are two separate boxes.for, if, while, and class cannot be names; Python has set these words aside for its own work.| Name | Valid? | Why |
|---|---|---|
latte_price | Yes | Lowercase, words separated by an underscore |
latte2 | Yes | The digit is at the end, not at the start |
2latte | No | Starts with a digit |
latte-price | No | The hyphen is taken to be a minus operator |
latte price | No | Contains a space |
for | No | A Python keyword |
When you write a name that breaks a rule, Python stops without running a single line of the program and points to the problem line. For example, for 2latte = 4.25 it says SyntaxError: invalid decimal literal: it tried to read something that starts with a digit as a number and then got stuck on the letters. For latte price = 4.25 it only says SyntaxError: invalid syntax. The message does not always state the reason clearly; but if you look at the name on the line it points to and compare it with the rules above, you will find the problem quickly.
Not every name that follows the rules is a good name. x = 4.25 works, but three weeks later, when you come back to your code, you will not remember what x was. latte_price = 4.25 explains itself; a well-chosen name leaves no need for a comment. PEP 8, the Python community's shared style guide, recommends lowercase letters and underscores between words in variable names: total_amount, daily_revenue. Letters outside the English alphabet (such as é or ü) technically work, but it is a common habit to avoid them in names so that nothing breaks across different keyboards and tools.
Choose the right status for each name.
For each row, pick its match from the list, then check.
latte_price2lattelatte-pricelatte priceforlatte2Updating is most useful when you are building something up. Ada starts the register at zero in the morning; with every sale, the value in the box goes up by the amount of the sale. Read the line register += 4.25 as "add 4.25 on top of what is in the register".
register = 0 register += 4.25 register += 2.00 print("Register:", register)
OutputRegister: 6.25The register was first 0, became 4.25 when a latte was sold, and 6.25 when a cookie was sold. Every line adds on top of the last value in the box; that is why the order and number of the lines matter. Now it is your turn. Change the code below: add a third sale (a tea, 1.25), then take 2.50 out of the register as change. Work out the result in your head before you press the Run button, then run it and check yourself.
Try it now· not graded; doesn't affect progress
Variables and updates do not belong only to the café; in daily life the same pattern appears everywhere a value changes over time. There is 20 on a bus card, and every ride costs 2. Let's make the same update in two ways: first the long way, then the shortcut.
balance = 20 ticket = 2 balance = balance - ticket balance -= ticket print("Left:", balance)
OutputLeft: 16The third and fourth lines do the same job; both take one ticket off the balance. After two rides, 16 is left. Now imagine the fare goes up, and let's add a line to the end of the program.
What is printed if the line ticket = 2.5 is added right before the print line in Example 4?
balance = 20 ticket = 2 balance = balance - ticket balance -= ticket ticket = 2.5 print("Left:", balance)
Getting a `NameError` because of an uppercase-lowercase or spelling difference. Ada defined the price with a capital letter and used it with a lowercase one:
Latte = 4.25
print(latte)Python gives this error:
OutputNameError: name 'latte' is not defined. Did you mean: 'Latte'?Read the message: "The name latte is not defined. Did you mean Latte?" For Python, Latte and latte are two separate boxes, and a box named latte was never created. The same error appears when you misspell the name (late) or use the variable before creating it: if the line print(cookie) comes before the line cookie = 2.00, you get NameError: name 'cookie' is not defined. The fix: define the variable before you use it, and write its name exactly the same everywhere. The habit of always writing names in lowercase with underscores prevents most of this mistake from the start.
name = value first calculates the right side, then puts the result into the name on the left. = is assignment, not equality.register = register + 4.25 and its shortcut register += 4.25 update the value from itself (-= and *= exist too). A result that was already calculated does not change by itself; you have to run the calculation again.latte_price explains the code by itself.Next lesson: We will learn to do math with numbers in Python, sales tax, rounding, and splitting a bill.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Order matters too: a variable must be defined before the line where it is used. Python runs lines one by one from top to bottom; it cannot look inside a box that has not been created yet.
Ada sells three cookies, gives a 0.50 discount, and prints the amount to pay. Put the lines in an order that will run.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order