Lesson 3 of 52First steps
Numbers and Strings
Do arithmetic without surprises, understand float precision, and build text with f-strings and indexing.
Almost every program does two things constantly: calculates with numbers and builds text for people to read. Prices, durations, percentages, log lines, error messages. This lesson covers the operators you will use daily, the one float quirk that bites everyone once, and f-strings, the modern way to format output.
Arithmetic operators
Python's maths operators work mostly as you would expect, with three you may not have met before.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 7 * 3 | 21 |
/ | true division, always a float | 7 / 2 | 3.5 |
// | floor division, rounds down | 7 // 2 | 3 |
% | modulo: the remainder | 7 % 2 | 1 |
** | power | 2 ** 10 | 1024 |
// and % are a pair. // tells you how many whole times something fits, and % tells you what is left over. Together they split any amount into units: 135 minutes is 135 // 60 hours and 135 % 60 minutes.
Press Run (⌘ Enter) to see what happens.Precedence follows school maths: ** first, then * / // %, then + -. When in doubt, add parentheses; they cost nothing and help the next reader.
One detail trips people up: // rounds down toward negative infinity, not toward zero. So -7 // 2 is -4, not -3. And % follows the same rule, so its result has the sign of the right-hand number.
What does this print?
print(17 // 5, 17 % 5) print(-7 // 2)
Ints are unbounded, floats are not exact
Python's int has no size limit. In many languages a whole number overflows after about 9.2 quintillion (2⁶³). Python just keeps going, using more memory as needed.
Press Run (⌘ Enter) to see what happens.Floats are different. A float is stored in binary with about 15 to 17 significant digits, and most decimal fractions (like 0.1) cannot be written exactly in binary, the same way 1/3 cannot be written exactly in decimal. The tiny errors usually stay hidden, until they do not:
Press Run (⌘ Enter) to see what happens.This is not a Python bug; JavaScript, Java and C give the same answer. The practical rules:
- Never compare floats with
==. Usemath.isclose(a, b). - For money, do not use floats. Store whole cents as an
int, or use thedecimalmodule. round(x, 2)rounds for display. It does not fix the stored value.
total equals 0.3. What is the right way?Strings: quotes and escapes
A string (str) is a sequence of characters. You can write one with single quotes or double quotes; they mean exactly the same thing. Pick the one that saves you escaping: "it's" or 'she said "hi"'.
Some characters cannot be typed directly, so you use an escape sequence: a backslash followed by a code.
| Escape | Means |
|---|---|
\n | newline |
\t | tab |
\\ | a real backslash |
\" or \' | a quote inside a string using the same quote |
Joining strings is called concatenation and uses +. * repeats a string. Mixing a string and a number with + is a TypeError, so convert with str() first.
Press Run (⌘ Enter) to see what happens.f-strings: the way to format
Gluing strings with + and str() gets ugly fast. An f-string (formatted string literal) is a string with an f before the quote. Anything inside {} is evaluated as Python and inserted.
Press Run (⌘ Enter) to see what happens.After the expression you can add a colon and a format spec to control how it looks. These are the ones you will use most:
Press Run (⌘ Enter) to see what happens.The last one, f"{price = }", is a debugging shortcut: it prints both the expression and its value. Handy when you are hunting a bug with print statements.
What does this print?
total = 9.876
count = 4
print(f"{count} items, {total:.2f} each")Match each f-string to its output, given x = 0.5.
Length, indexing and immutability
len(s) gives the number of characters. You can get a single character by its index, its position, using square brackets. Indexes start at 0, and negative indexes count from the end.
len("PYTHON") is 6. The positions are numbered 0 to 5.
Strings are immutable: once created, they cannot be changed. Methods that seem to change a string actually return a new one. If you try to assign to an index, Python refuses:
Press Run (⌘ Enter) to see what happens.(word[1:] means "from index 1 to the end". That is slicing, which you will use a lot in the lists lesson.)
What does this print?
s = "keyboard" print(len(s), s[0], s[-1], s[3])
Seconds to a clock
Write to_clock(seconds) that turns a number of seconds into an H:MM:SS string. Minutes and seconds always have two digits. Hours can be any size (no days).
to_clock(3725) → "1:02:05"
to_clock(59) → "0:00:59"
to_clock(90061) → "25:01:01"seconds is a whole number, 0 or more.
Split the bill
Write split_bill(total, people, tip_percent) that adds the tip to the total, splits it evenly, and returns each person's share rounded to 2 decimal places.
split_bill(100, 4, 20) → 30.0
split_bill(59.99, 3, 15) → 23.0people is at least 1.
- floor division (//)
- Divides and rounds down toward negative infinity.
7 // 2is3,-7 // 2is-4. - modulo (%)
- The remainder after floor division.
n % 2 == 0means n is even. - float precision
- Floats are binary approximations, so
0.1 + 0.2is0.30000000000000004. Compare withmath.isclose. - f-string
- A string starting with
fwhere{expression}is evaluated and inserted, with optional format specs like:.2f. - index
- A position in a sequence, starting at 0. Negative indexes count from the end.
- immutable
- Cannot be changed after creation. Strings, ints and floats are immutable; operations return new objects.