2. Calculating with numbers and working with text

Almost every script you write at work calculates something or tidies up text. A total price, an allowance, an invoice number, an email address that someone has typed carelessly. Calculation is built into Python, but the result is not always the type you expect. And text that you get from a user or from an export is rarely as clean as you would like.

Learning objectives

After this chapter:

  • Do you know the difference between a int en een float en zie je welk type een berekening oplevert.
  • Use the arithmetic operators, including floor division and modulo.
  • Convert your values with int(), float() en str().
  • You build neat output lines with f-strings and display amounts with two decimal places.
  • Clean up your text with string methods and extract parts of it with slicing.

Integers and floating-point numbers

Python has two kinds of numbers. An int is een heel getal, zoals het aantal cursusdagen. Een float is een getal met een decimale punt, zoals een prijs van 395.50. Let op die punt: Python schrijft decimalen met een punt, niet met een komma. Een komma betekent in Python iets anders, namelijk dat er twee losse waarden staan.

prijs.py

prijs_per_dag = 395
dagen = 3
totaal = prijs_per_dag * dagen
print(totaal)
print(type(totaal))
print(type(395.50))

Output

1185
<class 'int'>
<class 'float'>

Multiplying two whole numbers gives another whole number. Division works differently. The ordinary division with / levert altijd een float op, ook als de deling precies uitkomt. Daarnaast zijn er drie operatoren die je in het begin minder snel kent: // is de gehele deling (hoe vaak past het er helemaal in), % geeft de rest die overblijft, en ** is machtsverheffen.

rekenen.py

print(1185 / 3)
print(1185 // 400)
print(1185 % 400)
print(2 ** 10)

Output

395.0
2
385
1024

1185 divided by 3 is exactly 395, but Python writes 395.0: it has become a float. 400 fits into 1185 twice in full, and that leaves 385. Two to the power of ten is 1024.

Example

Ayla is seating 38 people at tables of 6 for a staff event. How many tables does she need? With ordinary division she gets 6.333..., and she can't order tables with that. With // en % wel:

tafels.py

deelnemers = 38
per_tafel = 6
volle_tafels = deelnemers // per_tafel
over = deelnemers % per_tafel
print("Volle tafels:", volle_tafels)
print("Deelnemers over:", over)
if over > 0:
    print("Tafels nodig:", volle_tafels + 1)

Output

Volle tafels: 6
Deelnemers over: 2
Tafels nodig: 7

Six tables are full, two people are left over, so a seventh table is needed. You need the same calculation for boxes per pallet, participants per group or hours in whole working days.

Converting values

Adding a number and a text produces an error, because Python doesn't guess what you mean. So you convert it yourself: int() maakt er een heel getal van, float() een kommagetal en str() een tekst.

conversie.py

ingetypt = "4"
deelnemers = int(ingetypt)
print(deelnemers * 395)
print(float("395.50"))
print(int(296.75))
print(round(296.75))
print("Totaal: " + str(1185))

Output

1580
395.5
296
297
Totaal: 1185

Pay attention to the third and fourth lines. int(296.75) rondt niet af maar kapt de cijfers achter de punt af: je krijgt 296. Wil je echt afronden, dan gebruik je round(), en dan krijg je 297.

In chapter 1 you saw that input() altijd tekst teruggeeft. Dit script moet de cursusprijs uitrekenen: de dagprijs maal het aantal dagen, plus 50 euro inschrijfkosten. Het stopt met een foutmelding:

totaal.py

dagprijs = 395
dagen = input("Aantal dagen: ")
totaal = dagprijs * dagen + 50
print("Totaal: " + totaal)

In the terminal

Aantal dagen: 3
Traceback (most recent call last):
  File "/tmp/cursus/totaal.py", line 3, in <module>
    totaal = dagprijs * dagen + 50
             ~~~~~~~~~~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str

The error appears on line 3, but the cause is one line higher. dagen is de tekst "3". dagprijs * dagen is daardoor geen fout: een getal maal een tekst herhaalt de tekst, dus dat levert een tekst van 395 drieën op. Pas bij + 50 gaat het mis, want tekst plus getal mag niet. De onderste regel zegt het precies: je kunt alleen een str aan een str plakken, niet een int. Je zet int() om de invoer en draait opnieuw:

totaal.py

dagprijs = 395
dagen = int(input("Aantal dagen: "))
totaal = dagprijs * dagen + 50
print("Totaal: " + totaal)

In the terminal

Aantal dagen: 3
Traceback (most recent call last):
  File "/tmp/cursus/totaal.py", line 4, in <module>
    print("Totaal: " + totaal)
          ~~~~~~~~~~~^~~~~~~~
TypeError: can only concatenate str (not "int") to str

Now it gets stuck on line 4, with the same message. totaal is nu een getal, en dat kun je niet aan de tekst "Totaal: " plakken. Met str(totaal) maak je er eerst tekst van:

totaal.py

dagprijs = 395
dagen = int(input("Aantal dagen: "))
totaal = dagprijs * dagen + 50
print("Totaal: " + str(totaal))

In the terminal

Aantal dagen: 3
Totaal: 1235

Neat output lines with f-strings

Joining text and numbers together with + en str() werkt, maar wordt snel onleesbaar. Een f-string is handiger. Je zet de letter f direct vóór het aanhalingsteken. Alles wat je daarbinnen tussen accolades zet, rekent Python uit en voegt hij in als tekst. Tussen de accolades mag ook een berekening staan. Achter de waarde kun je met een dubbele punt aangeven hoe hij eruit moet zien: :.2f toont een getal met precies twee cijfers achter de punt, wat je bij bedragen bijna altijd wilt.

fstring.py

naam = "Python programmeren basis"
dagen = 3
dagprijs = 395
print(f"{naam} duurt {dagen} dagen en kost {dagen * dagprijs} euro.")

prijs = 395
btw = prijs * 0.21
print(f"Prijs: {prijs} euro")
print(f"Btw: {btw:.2f} euro")
print(f"Totaal: {prijs + btw:.2f} euro")

Output

Python programmeren basis duurt 3 dagen en kost 1185 euro.
Prijs: 395 euro
Btw: 82.95 euro
Totaal: 477.95 euro
Example

Mark drives to customers for work and claims his kilometres every month. His employer reimburses 23 cents per kilometre. This month he made three trips: 137, 42 and 88 kilometres.

kilometers.py

ritten = 137 + 42 + 88
vergoeding = 0.23
bedrag = ritten * vergoeding
print(bedrag)
print(f"Gereden: {ritten} km")
print(f"Vergoeding: {bedrag:.2f} euro")

Output

61.410000000000004
Gereden: 267 km
Vergoeding: 61.41 euro

The first line of the output is a surprise: 61.410000000000004 instead of 61.41. That is not a mistake in Mark's script. A computer stores decimal numbers in the binary system, and in that system 0.23 cannot be written exactly, just as a third cannot be written exactly in the decimal system (0.333...). The difference is far behind the decimal point. With :.2f toont Python het bedrag afgerond op centen, en daar klopt het gewoon.

You can see it for yourself with the best-known sum in Python:

floats.py

print(0.1 + 0.2)
print(f"{0.1 + 0.2:.2f}")

Output

0.30000000000000004
0.30

So you always display amounts with :.2f, en twee kommagetallen uit een berekening vergelijk je nooit met ==.

Tip

If you forget the f, you don't get an error message but the literal text {naam} op je scherm. Zie je accolades in je uitvoer, dan weet je meteen waar het misging.

Cleaning up text with string methods

Using a dot after a value, you call a method: a function that belongs to that type of value. A string has dozens of them. You will see four of them again and again. strip() haalt spaties, tabs en regeleindes weg aan het begin en het eind, onmisbaar bij tekst die iemand heeft ingetypt. upper() en lower() zetten alles in hoofdletters of kleine letters, handig als je twee namen wilt vergelijken zonder dat hoofdletters roet in het eten gooien. replace(oud, nieuw) vervangt elk stuk tekst door iets anders. En startswith() en endswith() geven True of False terug, afhankelijk van of de string met die tekst begint of eindigt.

strings.py

invoer = "  python Programmeren Basis  "
titel = invoer.strip()
print(titel)
print(titel.upper())
print(titel.replace("Basis", "Gevorderd"))
print(titel.startswith("python"))
print(len(titel))

Output

python Programmeren Basis
PYTHON PROGRAMMEREN BASIS
python Programmeren Gevorderd
True
25

A string never changes by itself. Every method returns a new string, and the original stays as it was. If you want to keep the result, give it a name:

strings.py

code = "py-bas-2026"
code.upper()
print(code)
code = code.upper()
print(code)

Output

py-bas-2026
PY-BAS-2026

The second line does calculate the uppercase version, but discards it straight away. Only with code = code.upper() bewaar je hem.

Example

Linda manages the newsletter list. Colleagues type in addresses from business cards, with spaces before and after and capital letters wherever they happen to fall. The same address written in two different ways means the customer receives the newsletter twice. She cleans up each address before it goes into the list:

mail.py

ingetypt = "  J.deVries@Bakkerij-Holtkamp.NL "
adres = ingetypt.strip().lower()
print(adres)
print(adres.endswith(".nl"))
print(adres.replace("j.devries", "info"))

Output

j.devries@bakkerij-holtkamp.nl
True
info@bakkerij-holtkamp.nl

You can chain methods together: strip() geeft een string, en daar plak je direct lower() achter. Python voert ze van links naar rechts uit. Nu lijken twee adressen alleen nog op elkaar als ze echt hetzelfde zijn.

Extracting parts of a text with slicing

Every character in a string has a position, the index. Counting starts at 0. With a minus sign you count from the end: -1 is the last character. Between square brackets you request a single character, or a whole section by using a colon. The latter is called slicing.

slicing.py

naam = "Python"
print(naam[0])
print(naam[-1])
print(naam[0:3])
print(naam[3:])
print(naam[::-1])

Output

P
n
Pyt
hon
nohtyP
The word Python in six boxes. Above each box is the position counted from the front, 0 to 5, and below it the position counted from the back, -6 to -1. Underneath are two bars: name[0:3] gives Pyt, name[3:] gives hon.
With a slice, the start number is included and the end number is not.

At naam[0:3] krijg je de posities 0, 1 en 2: het startgetal doet mee, het eindgetal niet. Laat je een getal weg, dan gebruikt Python het begin of het eind van de string: naam[3:] is alles vanaf positie 3. Een derde getal is de stapgrootte, en -1 als stap draait de tekst om.

Slicing is especially useful for codes with a fixed structure. The trainer from the schedule codes each course as PY-BAS-2026: language, level and year. With slicing, you can separate those three:

code.py

code = "PY-BAS-2026"
print(f"Taal: {code[:2]}")
print(f"Niveau: {code[3:6]}")
print(f"Jaar: {code[-4:]}")

Output

Taal: PY
Niveau: BAS
Jaar: 2026
Example

In Sander's accounts department, invoice numbers look like F2026-00418: an F, the year, a hyphen and a five-digit sequence number. For a checking script, he wants to use the last number to generate the next one.

factuur.py

factuurnummer = "F2026-00418"
print(factuurnummer[1:5])
print(int(factuurnummer[-5:]))
print(int(factuurnummer[-5:]) + 1)
volgende = f"F{factuurnummer[1:5]}-{int(factuurnummer[-5:]) + 1:05d}"
print(volgende)

Output

2026
418
419
F2026-00419

factuurnummer[1:5] slaat de F over en neemt de vier cijfers van het jaar. factuurnummer[-5:] neemt de laatste vijf tekens, en int() maakt daar het getal 418 van, zonder de voorloopnullen. Na de optelling moeten die nullen er weer bij. Dat doet :05d in de f-string: een heel getal (d), vijf tekens breed, aangevuld met nullen.

Exercise

You start with titel = " python programmeren basis ", met twee spaties ervoor en erachter. Je schrijft een script dat vier regels toont: de titel zonder de spaties, dezelfde titel in hoofdletters, met een f-string de zin "Deze titel telt ... tekens." met het aantal tekens van de opgeschoonde titel, en alleen de eerste zes tekens van de opgeschoonde titel. Zo hoort het eruit te zien:

Output

python programmeren basis
PYTHON PROGRAMMEREN BASIS
Deze titel telt 25 tekens.
python

If it doesn't work in one go, first save the cleaned-up title under a name of its own, for example schoon = titel.strip(), en werk je verder met schoon.

Numbers and text at a glance

  • A int is een heel getal, een float een getal met een punt. / geeft altijd een float.
  • // is de gehele deling, % de rest, ** machtsverheffen.
  • int(), float() en str() zetten om. int() kapt af, round() rondt af.
  • An f-string starts with f; you put values and calculations between curly brackets. :.2f toont twee decimalen.
  • Decimal numbers are not always exact: display amounts rounded.
  • strip(), lower(), upper(), replace() geven een nieuwe string; het origineel blijft gelijk.
  • Counting starts at 0, and -1 is the last character. With [start:eind] doet het eindgetal niet mee.
Knowledge check

What do 38 // 6 en 38 % 6?

You write code = "py-bas-2026" en daarna code.upper(). Wat toont print(code)?

What does this return "F2026-00418"[1:5]?

Share this chapter: