Skip to content

Lesson 3 of 52First steps

Numbers and Strings

Do arithmetic without surprises, understand float precision, and build text with f-strings and indexing.

14 min read0/5 questions

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.

OperatorMeaningExampleResult
+ - *add, subtract, multiply7 * 321
/true division, always a float7 / 23.5
//floor division, rounds down7 // 23
%modulo: the remainder7 % 21
**power2 ** 101024

// 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.

Python
minutes = 135print(minutes // 60, "hours and", minutes % 60, "minutes") print(10 % 2 == 0) # the classic "is it even?" testprint(2 ** 0.5) # a fractional power is a square root
Output
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.

Predict the outputPython

What does this print?

print(17 // 5, 17 % 5)
print(-7 // 2)
Need a nudge? Hints walk you through it.

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.

Python
print(2 ** 100)print(len(str(2 ** 10_000)), "digits")
Output
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:

Python
print(0.1 + 0.2)print(0.1 + 0.2 == 0.3) import mathprint(math.isclose(0.1 + 0.2, 0.3))
Output
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 ==. Use math.isclose(a, b).
  • For money, do not use floats. Store whole cents as an int, or use the decimal module.
  • round(x, 2) rounds for display. It does not fix the stored value.
Quick check
You need to check whether a computed total equals 0.3. What is the right way?
Need a nudge? A hint rules out a wrong answer.

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.

EscapeMeans
\nnewline
\ttab
\\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.

Python
first = "Ada"greeting = "Hello, " + first + "!"print(greeting)print("ha" * 3)print("Line one\nLine two\tTabbed")print("Score: " + str(42))
Output
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.

Python
name = "Priya"items = 3price = 4.5 print(f"{name} bought {items} items")print(f"Total: {items * price}")
Output
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:

Python
price = 1234.5ratio = 0.4567n = 7 print(f"{price:.2f}") # 2 decimal places: 1234.50print(f"{price:,.2f}") # thousands separator: 1,234.50print(f"{ratio:.1%}") # as a percentage: 45.7%print(f"{n:03d}") # pad with zeros to width 3: 007print(f"[{n:>5}]") # right-align in 5 charactersprint(f"{price = }") # debug: shows the expression and its value
Output
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.

Predict the outputPython

What does this print?

total = 9.876
count = 4
print(f"{count} items, {total:.2f} each")
Need a nudge? Hints walk you through it.
Match the pairs0/4 matched

Match each f-string to its output, given x = 0.5.

Choose an item, then its match on the other side.

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.

Indexing the string "PYTHON"
P
0
Y
1
T
2
H
3
O
4
N
5

len("PYTHON") is 6. The positions are numbered 0 to 5.

1/4

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:

Python
word = "jello"# word[0] = "h" would raise TypeError: 'str' object does not support item assignmentfixed = "h" + word[1:]print(fixed)print(word) # the original is untouched
Output
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.)

Predict the outputPython

What does this print?

s = "keyboard"
print(len(s), s[0], s[-1], s[3])
Need a nudge? Hints walk you through it.
ChallengeEasy

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.

Python
def to_clock(seconds: int) -> str: # Use // and % to split seconds into hours, minutes and seconds. pass
ChallengeEasy

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.0

people is at least 1.

Python
def split_bill(total: float, people: int, tip_percent: float) -> float: # total with tip, divided by people, rounded to 2 places pass
Key terms
floor division (//)
Divides and rounds down toward negative infinity. 7 // 2 is 3, -7 // 2 is -4.
modulo (%)
The remainder after floor division. n % 2 == 0 means n is even.
float precision
Floats are binary approximations, so 0.1 + 0.2 is 0.30000000000000004. Compare with math.isclose.
f-string
A string starting with f where {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.