A program that remembers
In the first lesson you used Python as a calculator: print(7 * 24) worked something out and showed it. But the answer vanished as soon as it was printed. Real programs need to remember things: the score in a game, the money in an account, the name of the person who is logged in, how many steps you have walked today.
Suppose Mei is saving for a bicycle that costs 120 (in whatever currency you like). She has saved 30 so far and puts aside 15 each week. How many more weeks must she save? You could type (120 - 30) // 15 and get 6. But look at this version:
price = 120
saved = 30
weekly = 15
weeks_left = (price - saved) // weeklyIt computes the same thing, yet it reads almost like a sentence, and if the price changes you change one line. The names price, saved and weekly are variables, and the numbers and text they name are values. This lesson is about both, and about the expressions that combine them.
Every value has a type
Everything a program works with is a value: the number 42, the number 3.5, the text "Nairobi", the answer True. And every value has a type, which says what kind of thing it is and so what you can do with it. You can multiply two numbers. You can turn text into capital letters. But multiplying "Nairobi" by "Lima" makes no sense, and Python will say so.
Analogy, not a formal construction
Types are like units in a science lesson. You can add 3 metres to 2 metres, and you can multiply metres by metres to get square metres, but adding 3 metres to 2 kilograms is meaningless. Python checks the "kind" of every value before it combines them, the way a careful scientist checks units.
Python has four basic types you will use constantly:
| Type | Name in Python | Examples | Used for |
|---|---|---|---|
| whole numbers | int (integer) | 0, 7, -15, 2026 | counting, positions, years |
| numbers with a fractional part | float (floating-point number) | 3.5, -0.25, 2.0 | measurements, averages, prices |
| text | str (string) | "hello", 'Ama', "42" | names, messages, anything written |
| true or false | bool (Boolean) | True, False | answers to yes-or-no questions |
You can always ask Python for a value's type with the built-in function type. Notice that "42", in quotes, is a string: it is the two characters 4 and 2, not the number forty-two.
Definitions
Definition— value and type
A value is a piece of data a program works with. Its type (such as int, float, str or bool) determines which operations make sense for it.
Definition— expression
An expression is a piece of code that Python can work out, or evaluate, to get a value. 7, 2 + 3 * 4, price - saved and "ab" * 3 are all expressions.
Definition— variable and assignment
A variable is a name that refers to a value. An assignment statement, written name = expression, first evaluates the expression on the right, then makes the name on the left refer to the result. If the name already referred to something, it now refers to the new value instead.
Numbers and arithmetic
Python's arithmetic operators are:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | addition | 7 + 2 | 9 |
- | subtraction | 7 - 2 | 5 |
* | multiplication | 7 * 2 | 14 |
/ | division | 7 / 2 | 3.5 |
// | floor division (whole number of times) | 7 // 2 | 3 |
% | remainder (also called modulo) | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Two kinds of division
The / operator always gives a float, even when the division comes out exactly: 8 / 2 is 4.0, not 4. If you want a whole-number answer, use // and % together, the way you learned division with remainder in primary school: 47 sweets shared among 6 children is 7 each, with 5 left over. In Python, 47 // 6 is 7 and 47 % 6 is 5.
These two operators are surprisingly useful:
n % 2is0exactly whennis even.n % 10is the last digit of a positive whole numbern, andn // 10is the number with its last digit removed.- 135 minutes is
135 // 60hours (2) and135 % 60minutes (15).
The remainder operator is the "clock arithmetic" of Lumenary Math's remainders and modular arithmetic.
Order of operations
When an expression has several operators, Python follows rules of precedence, much like the order of operations you may have learned in maths:
- Parentheses first.
- Then
**(powers). - Then
*,/,//and%, from left to right. - Then
+and-, from left to right.
Example— Evaluating 2 + 3 * 4 ** 2 step by step
- The power goes first:
4 ** 2is16, leaving2 + 3 * 16. - Then the multiplication:
3 * 16is48, leaving2 + 48. - Then the addition:
50.
If you meant something else, say so with parentheses: (2 + 3) * 4 is 20. Parentheses cost nothing and make your meaning obvious to the next reader, so use them whenever you are unsure.
One rule catches nearly everyone once: ** is done before a minus sign in front of a number. So -3 ** 2 means -(3 ** 2), which is -9. If you want "minus three, squared", write (-3) ** 2.
Run this, then change the numbers and predict each line before you run it again:
print(type(42), type(3.5), type("Nairobi"), type(True))
print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2) # true division: always a float
print(8 / 2) # still a float, even though it divides exactly
print(47 // 6) # how many whole times 6 fits into 47
print(47 % 6) # what is left over
print(2 ** 10)
print(2 + 3 * 4 ** 2) # power, then multiply, then add
print((2 + 3) * 4)
print(-3 ** 2, (-3) ** 2)
# Comparisons give Boolean values
print(3 > 2, 10 == 9 + 1, "a" == "A")The last line shows the fourth type in action. A comparison such as 3 > 2 is an expression whose value is True or False. Notice that a double equals sign == asks "are these equal?". You will use comparisons a great deal in the next lesson.
Variables: names for values
An assignment like saved = 30 does two things, in this order:
- Python evaluates the right-hand side, getting the value
30. - Python makes the name
savedrefer to that value.
That order matters, because it explains a line that looks like nonsense in maths:
saved = saved + 15In algebra, has no solution. In Python, = is not a statement that two things are equal; it is an instruction: "work out the right side, then let the left name refer to it". So Python looks up the current value of saved (say 30), adds 15 to get 45, and then makes saved refer to 45. Because this pattern is so common, Python has a shorthand: saved += 15 means the same thing. There are also -=, *= and friends.
Analogy, not a formal construction
Think of a variable as a name tag tied to a value, not as the value itself. saved = 30 ties the tag "saved" to the number 30. saved = saved + 15 works out 45 and moves the tag onto it. One value can wear several tags at once, and a tag can be moved at any time, but it is only ever on one value.
Tracing assignments by hand
To understand a program, programmers often trace it: they go through it line by line, keeping a table of what each variable refers to.
a = 5
b = a
a = a + 1| After line | a | b |
|---|---|---|
a = 5 | 5 | (not yet defined) |
b = a | 5 | 5 |
a = a + 1 | 6 | 5 |
The second line makes b refer to the value that a refers to at that moment, which is 5. When the third line moves the tag a to 6, b is not affected. Variables are not like spreadsheet cells, which recalculate automatically when something they depend on changes.
Choosing names
Variable names may contain letters, digits and the underscore _, but may not start with a digit or contain spaces. Python is case-sensitive: Total and total are different names. A few words, such as if, for and True, are reserved by Python. By convention, Python programmers write names in lowercase with underscores between words, like weeks_left (this style is called snake case).
Good names describe what the value means: price beats p, and weeks_left beats x2. Code is read many more times than it is written, often by someone else, so a well-chosen name is a kindness.
price = 120
saved = 30
weekly = 15
still_needed = price - saved
weeks = still_needed // weekly
print("Still needed:", still_needed)
print("Weeks of saving:", weeks)
# One week passes
saved += weekly
print("Saved now:", saved)
print("still_needed has not changed by itself:", still_needed)
still_needed = price - saved # recompute it explicitly
print("Recomputed:", still_needed)Working with text
A string is written between quotation marks, either double "…" or single '…'; both mean exactly the same, and you can pick whichever avoids a clash: "It's raining". Some useful operations:
+joins strings:"Accra" + ", " + "Ghana"is"Accra, Ghana".*repeats a string:"-" * 10is ten dashes.len(s)gives the number of characters ins.
f-strings: putting values into text
Joining strings with + gets clumsy when you mix in numbers. Python's neatest tool for building text is the f-string: put an f just before the opening quote, and write any expression inside curly braces. Python evaluates each expression and puts its value into the text.
name = "Tomás"
age = 12
print(f"{name} is {age} years old and will be {age + 1} next year.")After the expression you can add a colon and a format specification. The most useful one is :.2f, which means "show as a float with 2 digits after the decimal point", which is perfect for prices.
Converting between types
"12" + "12" is "1212", because joining two strings just puts them side by side. To do arithmetic with text that contains digits, convert it first:
int("42")is the integer42;float("2.5")is the float2.5.str(2026)is the string"2026".int(3.99)is3: converting a float to an int chops off the fractional part. To round to the nearest whole number, useround(3.99), which is4.
This matters because, in a full Python program, the built-in function input() reads what a user types, and it always gives back a string, even if the user typed digits. (The runnable boxes in these lessons don't ask for typed input, so that the course's own tests can run them automatically.)
city = "Accra"
country = "Ghana"
print(city + ", " + country)
print(len(city), "letters")
print("=" * 24)
mangoes = 6
price_each = 2.5
total = mangoes * price_each
print(f"{mangoes} mangoes at {price_each} cedis each cost {total} cedis.")
print(f"Shown with two decimals: {total:.2f}")
age_text = "12"
print(age_text + age_text) # joins the text
print(int(age_text) + int(age_text)) # adds the numbers
print(str(2026) + "!")
print(int(3.99), round(3.99), float(7))A surprise about floats
Run this and look carefully at the first line of output.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2))
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # "close enough" is the right test
print(2 ** 100) # ints can be as big as you like, and are exact
print(1e20 + 1 - 1e20) # floats keep only about 16 significant digitsIs Python bad at arithmetic? No. Computers store floats in binary (base 2), and most decimal fractions, including 0.1, cannot be written exactly in binary, just as cannot be written exactly in decimal (0.3333… goes on for ever). So 0.1 is stored as a binary number extremely close to 0.1, and the tiny errors can show up after arithmetic. A float keeps about 15 to 17 significant decimal digits, which is plenty for measurements, but it is not exact.
Three practical rules follow:
- Don't compare floats with
==. Check whether they are close:abs(x - y) < 1e-9. (Here1e-9is Python's way of writing .) - Round when you display, not while you calculate. Use
round(x, 2)or an f-string with:.2ffor the final output. - Count money in whole units. Programs that handle money usually store amounts as whole numbers of the smallest unit (cents, paise, centavos), as
ints, which are exact. Python's integers can grow as large as memory allows, so2 ** 100is computed exactly.
You will see how numbers are really stored as bits in a later lesson, Bits and bytes.
Putting it together: which pack is cheaper?
Here is a small, realistic problem that uses everything in this lesson. In a market in Lima, rice is sold in two pack sizes: a 5 kilogram bag for 32.50 soles and a 2 kilogram bag for 13.80 soles. Which is the better deal, and by how much per kilogram?
Example— Comparing unit prices
The algorithm is one you may already use when shopping: work out the price of one kilogram in each case, then compare.
big_price = 32.50
big_kg = 5
small_price = 13.80
small_kg = 2
big_per_kg = big_price / big_kg # 6.5
small_per_kg = small_price / small_kg # 6.9
saving = small_per_kg - big_per_kg
print(f"Big bag: {big_per_kg:.2f} per kg")
print(f"Small bag: {small_per_kg:.2f} per kg")
print(f"The big bag saves {saving:.2f} soles per kg")
print("Big bag is cheaper per kg:", big_per_kg < small_per_kg)Read it as a story. The first four lines name the facts of the problem. The next three lines are the processing: each one is an expression whose value is given a name, and later lines use those names. The last four lines are the output, and they use :.2f because a price per kilogram such as 0.40000000000000036 (which is what the subtraction really produces, thanks to float rounding) would look silly on a sign. The final line prints a Boolean: the answer to a yes-or-no question.
Notice what the names buy you. If the market changes its prices tomorrow, you edit two numbers at the top and everything else stays correct. And anyone reading the code, including you in six months, can see why each number is what it is.
Names, types and professional code
In Python, a variable has no fixed type: the same name can refer to an int now and a str later. That flexibility is convenient but can hide mistakes, so many teams add type hints, such as price: float = 32.50, which tools can check before the program runs. Python itself ignores them when running the code. You will meet them properly in Types and functional programming; for now, choosing clear names and keeping each variable to one meaning gets you most of the benefit.
Common mistakes and error messages
Misconception
"= means equals." In Python, a single = is assignment: an instruction to make a name refer to a value. To ask whether two things are equal, use ==. Mixing them up is one of the most common beginner mistakes in every programming language that uses this notation.
Misconception
"If I change a, then b = a + 1 changes too." No. b was given a value when that line ran. Later changes to a don't reach back and update b. If you want b to reflect the new a, run the assignment again.
Misconception
"7 / 7 is an integer." / always produces a float, so 7 / 7 is 1.0. Use // when you want a whole-number result.
Misconception
"print("total") prints my total." The quotation marks make it the five-letter string total. To print the value of the variable, leave out the quotes: print(total).
When Python cannot carry out an instruction, it stops and reports an error. The last line of the error message names the kind of error, and these four are the ones you'll meet first:
| Error | Typical cause | Example |
|---|---|---|
NameError | a name used before it was assigned, or misspelled | print(totl) |
TypeError | an operation on the wrong type of value | "Age: " + 12 |
SyntaxError | code that breaks Python's grammar | print("hello) (unclosed quote) |
ZeroDivisionError | dividing by zero | 5 / 0 |
The TypeError example deserves a closer look: Python refuses to guess whether you wanted to join text or add numbers. Fix it by saying which you meant: "Age: " + str(12), or better, f"Age: {12}". You will learn to read full error reports in Finding and fixing mistakes.
Exercises
Predict before you run. The habit of guessing what code will do, and then checking, is the fastest way to learn.
1. Values, variables and expressions
Warm-upComputationalWhat value does Python give for this expression?
10 - 2 * 3 ** 2 + 4
2. Values, variables and expressions
Warm-upComputationalA teacher shares 50 pencils equally among 8 groups and keeps the rest. What do 50 // 8 and 50 % 8 give?
3. Values, variables and expressions
CoreComputationalWhat does print(type(9 / 3)) show?
4. Values, variables and expressions
CoreComputationalTrace this program by hand. What does it print?
x = 4
y = x * 2
x = x + 1
y = y - x
print(x, y)
5. Values, variables and expressions
CoreComputationalWhat does this print? Type exactly the output.
a = "3"
b = "4"
print(a + b)
6. Values, variables and expressions
CoreComputationalA race lasted total_seconds = 7384 seconds. Using // and %, set:
hoursto the number of whole hours,minutesto the number of whole minutes left over after the hours,secondsto the number of seconds left over after that.
Your code should still work if someone changes the value of total_seconds: use calculations, not numbers you worked out by hand. (Check: 2 hours, 3 minutes and 4 seconds.)
7. Values, variables and expressions
CoreComputationalUse an f-string to build a receipt line. With the values in the starter, line must be exactly:
6 mangoes at 0.75 each: 4.50
The total must be computed (quantity times price) and shown with exactly two decimal places using :.2f. The price should be shown with two decimals too.
8. Values, variables and expressions
Warm-upComputationalThis program stops with a TypeError. Run it to see the message, then fix it so that message is exactly "Kofi is 12 years old". Keep age as the number 12.
Further reading and resources
- The Python Tutorial: An informal introduction to Python · Python Software FoundationNumbers, text and first steps, with many small examples.
- Floating-point arithmetic: issues and limitations · Python Software FoundationWhy 0.1 + 0.2 is not exactly 0.3, explained carefully.
- Formatted string literals (f-strings) · Python Software Foundation
- Built-in types · Python Software FoundationThe reference for every operation on numbers, strings and booleans.