1. Your first Python script

Three lines of code are already a programme. You write a script like that, store values under a name, let the user type something in, and see how Python uses indentation to show what belongs together. And because something always goes wrong with your first scripts, you also learn to read an error message. That will save you more time over the coming weeks than anything else.

Learning objectives

After this chapter:

  • You write a script of several lines and run it.
  • Do you know what a built-in function is, and can you name five?
  • You store a value in a variable and use it again.
  • Do you see how indentation determines which lines belong together.
  • You ask for input with input() en reken je daarmee.
  • You read an error message from the bottom up and find the error in your code.

Text on screen with print()

The classic start of every programming course is displaying text. You create a folder for this course, open your text editor and put these three lines in a new file. You save it as rooster.py.

rooster.py

print("Cursusrooster najaar")
print("Python programmeren basis")
print("Excel gevorderd")

In the terminal, go to the folder containing the file and type python rooster.py. Python werkt het bestand regel voor regel af, van boven naar beneden. Drie regels leveren dus drie keer uitvoer op, in precies die volgorde.

Output

Cursusrooster najaar
Python programmeren basis
Excel gevorderd

The text between the quotation marks is called a string. Whether you use double or single quotation marks makes no difference, as long as the beginning and the end match.

Built-in functions

print hoef je niet zelf te maken. Het is een ingebouwde functie: kant-en-klare functionaliteit die altijd beschikbaar is, zonder dat je iets hoeft te laden. Je roept een functie aan door de naam te typen met haakjes erachter. Tussen de haakjes zet je wat de functie moet verwerken. Python heeft er een stuk of zeventig. Vijf kom je in het begin steeds tegen: print() toont iets op het scherm, len() geeft de lengte, bijvoorbeeld het aantal tekens van een tekst, input() vraagt de gebruiker iets te typen, round() rondt een getal af en type() vertelt je met wat voor soort waarde je te maken hebt.

functies.py

print(len("Python programmeren basis"))
print(round(1495.5))
print(type(3))
print(type("3"))

Output

25
1496
<class 'int'>
<class 'str'>

The course name is 25 characters long, including spaces. The number 3 is of the type int, een heel getal. Zet je het tussen aanhalingstekens, dan is het een str: tekst waarin toevallig een cijfer staat. Dat verschil lijkt klein, maar het is de oorzaak van een van de meest gemaakte fouten, verderop bij input().

Tip

Forgetting the brackets is the best-known beginner's mistake. If you type print "Hallo", dan weigert Python het bestand te draaien. In Python 3 zijn die haakjes verplicht, want print is een gewone functie.

Storing a value in a variable

With the = sign you give a value a name. Such a name is called a variable. After that you can use that name anywhere instead of the value itself. If you later give the same name a new value, the old one is gone.

rooster.py

cursus = "Python programmeren basis"
dagen = 3
print(cursus)
print("Aantal dagen:", dagen)
dagen = dagen + 1
print("Na de verlenging:", dagen)

Output

Python programmeren basis
Aantal dagen: 3
Na de verlenging: 4

The line dagen = dagen + 1 leest Python van rechts naar links: eerst rekent hij uit wat dagen + 1 is (4), en dan bewaart hij dat onder de naam dagen. Het isteken betekent in Python dus niet "is gelijk aan" maar "krijgt de waarde". Geef je print() meerdere dingen mee, gescheiden door komma's, dan zet Python er vanzelf een spatie tussen.

A name may contain letters, digits and the underscore, but must not start with a digit. It is best to choose names that say what they contain: prijs_lunch lees je over een maand nog, x2 niet. Python let op hoofdletters: Dagen en dagen zijn twee verschillende namen.

Indentation determines what belongs together

Where other languages use curly brackets to group lines, Python uses whitespace at the start of the line. That indentation is not formatting but meaning. A line ending in a colon announces a block, and all the lines that follow and are indented further to the right belong to that block. The word if komt in hoofdstuk 4 uitgebreid aan bod; hier zie je alleen wat de insprong doet.

rooster.py

cursus = "Python programmeren basis"
dagen = 3

if dagen > 2:
    print(cursus)
    print("Deze cursus duurt meerdere dagen.")
print("Einde rooster")

Output

Python programmeren basis
Deze cursus duurt meerdere dagen.
Einde rooster

The two indented lines only run if dagen groter is dan 2. De laatste regel staat weer helemaal links. Daarmee is het blok afgesloten en hoort die regel bij het hoofdprogramma: hij draait altijd. Verander je de eerste twee regels in een eendaagse cursus, dan slaat Python het blok over:

rooster.py

cursus = "Excel gevorderd"
dagen = 1

if dagen > 2:
    print(cursus)
    print("Deze cursus duurt meerdere dagen.")
print("Einde rooster")

Output

Einde rooster
Tip

Four spaces per level works best, and you never mix tabs and spaces in the same file. On your screen it looks the same, but Python counts differently and then reports an error that you cannot find by eye. Most editors automatically convert a tab into four spaces.

Asking for input with input()

With input() laat je je programma wachten tot de gebruiker iets typt en op Enter drukt. Wat je tussen de haakjes zet, verschijnt als vraag op het scherm. Het antwoord komt terug als tekst, die je in een variabele bewaart. In de terminal zie je de vraag, en daarachter wat de gebruiker typte.

zoeken.py

naam = input("Welke cursus zoek je? ")
print("Je zocht: " + naam)

In the terminal

Welke cursus zoek je? Python programmeren basis
Je zocht: Python programmeren basis

An important detail: input() geeft altijd tekst terug, ook als de gebruiker een getal typt. Wil je met dat getal rekenen, dan zet je het eerst om met int().

Example

Ayla is an office manager and arranges the lunch for an internal workshop every month. The number of participants varies, and the lunch costs 14 euros per person. She writes lunch.py:

lunch.py

deelnemers = int(input("Aantal deelnemers: "))
prijs_lunch = 14
print("Lunchkosten:", deelnemers * prijs_lunch, "euro")

In the terminal

Aantal deelnemers: 12
Lunchkosten: 168 euro

With 12 participants that is 168 euros. A week later a colleague takes int() weg, omdat de regel er zo ingewikkeld uitzag:

lunch.py

deelnemers = input("Aantal deelnemers: ")
prijs_lunch = 14
print("Lunchkosten:", deelnemers * prijs_lunch, "euro")

In the terminal

Aantal deelnemers: 12
Lunchkosten: 1212121212121212121212121212 euro

There is no error message, and that makes it treacherous. deelnemers is nu de tekst "12", en tekst maal een getal betekent in Python: die tekst zo vaak achter elkaar zetten. Veertien keer "12" geeft een rij van 28 cijfers. Met int() eromheen wordt het weer gewoon rekenwerk. Typt iemand "twaalf" in plaats van 12, dan stopt het programma wel, met een foutmelding. Die lees je zo meteen.

Reading an error message

If something goes wrong, Python stops and shows a traceback: a report of where it went wrong. Beginners see a block of English text and scroll away, but the last line is almost always enough. It states the type of error and a short explanation. This code contains a typo:

rooster.py

cursus = "Python programmeren basis"
print(cusus)

Output

Traceback (most recent call last):
  File "/tmp/cursus/rooster.py", line 2, in <module>
    print(cusus)
          ^^^^^
NameError: name 'cusus' is not defined. Did you mean: 'cursus'?

You read from bottom to top. The bottom line says what is wrong: a NameError, de naam cusus bestaat niet, en Python vraagt of je cursus bedoelde. De regels daarboven tonen welke code het was, met dakjes onder het stuk dat fout ging. En helemaal bovenaan staat waar: welk bestand en welk regelnummer. In de voorbeelden staan de bestanden in de map /tmp/cursus; bij jou staat daar het pad naar je eigen bestand.

A traceback with three marked parts. 1 What: the bottom line with NameError and the explanation; you start there. 2 Which code: the line print(cusus) with carets under the wrong word. 3 Where: the file and line number 2. An arrow from bottom to top.
Read the bottom line first. Only if that does not tell you enough do you look higher up.

In the beginning you keep running into the same three types of error. An SyntaxError betekent dat Python de regel niet begrijpt, bijvoorbeeld door een vergeten haakje of aanhalingsteken. Een IndentationError betekent dat de insprong niet klopt met de blokstructuur. Een NameError betekent dat je een naam gebruikt die nergens een waarde heeft gekregen, meestal door een typefout.

Example

Joost adapts Ayla's script for a fixed group of 12 and forgets a closing bracket:

lunch.py

deelnemers = 12
prijs_lunch = 14
print("Lunchkosten:", deelnemers * prijs_lunch, "euro"
print("Klaar")

Output

  File "/tmp/cursus/lunch.py", line 3
    print("Lunchkosten:", deelnemers * prijs_lunch, "euro"
         ^
SyntaxError: '(' was never closed

In the case of a SyntaxError draait er niets, ook regel 1 en 2 niet: Python leest eerst het hele bestand en weigert als er een regel tussen zit die hij niet begrijpt. De melding wijst naar regel 3 en zegt dat het haakje na print nooit is gesloten. Joost zet het haakje achter "euro" en het script werkt.

Ayla then tries what happens when someone types a word instead of a number:

lunch.py

deelnemers = int(input("Aantal deelnemers: "))

In the terminal

Aantal deelnemers: twaalf
Traceback (most recent call last):
  File "/tmp/cursus/lunch.py", line 1, in <module>
    deelnemers = int(input("Aantal deelnemers: "))
ValueError: invalid literal for int() with base 10: 'twaalf'

Now it is an ValueError: de waarde 'twaalf' kan int() niet omzetten. De onderste regel noemt die waarde letterlijk, dus je ziet meteen wat de gebruiker typte. Hoe je zo'n fout opvangt zonder dat het programma stopt, is een onderwerp van de training.

Exercise

You put these two lines in a file and run it. The script stops with an error message.

rooster.py

print("Cursusrooster najaar")
 print("Python programmeren basis")

You read the bottom line of the error message, find the cause and fix it. As a check, the script should then show two lines: Cursusrooster najaar and Python programmeren basis.

The message is IndentationError: unexpected indent: op regel 2 staat een spatie vóór print. Python leest die als het begin van een blok, terwijl er geen regel met een dubbele punt is waar dat blok bij hoort. Je haalt de spatie weg.

The first script in a row

  • A script is a text file with the extension .py. You start it with python rooster.py, en Python werkt het van boven naar beneden af.
  • You call a built-in function using brackets: print(), len(), input(), round(), type().
  • With naam = waarde bewaar je een waarde. Het isteken betekent "krijgt de waarde".
  • A colon introduces a block; the indented lines below it belong to it. Four spaces per level.
  • input() geeft altijd tekst. Met int() maak je er een getal van.
  • You read an error message from the bottom up: what, which code, where.
Knowledge check

Your script stops with a long error message. Where do you look first?

Someone types 12 at deelnemers = input("Aantal: "). Wat geeft deelnemers * 14?

Under a line with if dagen > 2: staan twee ingesprongen regels en dan een regel helemaal links. Wanneer draait die laatste regel?

Share this chapter: