In the last section we started writing programs. In this section we will learn more about how the computer interprets those instructions.
You will be able to run all the code directly here on mathplanet.com - but you can also write exactly the same code in a file on your computer and run it with IDLE - that we installed in the last section.
From top to bottom
Take a look at the following program:
We have a program consisting of four lines of code. Most often, each line is one instruction. Here, each instruction is print – which is used to print something on the screen.
The computer performs (or executes) each instruction in order from top to bottom. If you try running the example you will see the result is:
|Hello and welcome!
Here is the answer:
That is all, thank you!
Exactly the order in which the instructions are written. There will never be another, unexpected order. The proper word is determinism - we say that computers are deterministic. There is no randomness involved, they will always do exactly what they are told (even if it wasn't what you actually meant).
On line 3, more than one thing is happening:
print(1 + 2 + 3 + 4 + 5)
The computer is instructed to print something, but to know what it should print it must first do the calculation:
Once it knows it's \(15\), it can print that.
Therefore we also see that - just as in mathematics - stuff inside parentheses must be done first..
A baking recipe doesn't just contain instructions but also explanations, descriptions, or other information. In programming, we call all of these things "comments".
A comment in Python begins with the symbol #. Everything that comes after that sign is ignored by the computer and is only intended for human readers.
A normal program may therefore look like this:
# Greet the user print("Hello and welcome!") print("HärHere is the answer:") # Perform the calculation and print it print(1+2+3+4+5) # End the program print("hat is all, thank you!")
Comments can be very useful in keeping track of the different parts of our code. But remember that they must always start with # and that the computer doesn't understand them at all, or even read them. They are only meant for you, and for explaining the code for other humans.
In this video we look at a simple program and how important it is to write instructions in the right order.
- Algorithm: A description for how to solve a problem. A recipe is an example of an algorithm for cooking a certain dish. Programming is writing code to carry out steps of an algorithm.
- Instruction: A step in a program, might be one part of an algorithm.
- Comments: Extra text that can be added in our code to better keep track of it. In Python, they start with #. Everything that follows is only for human readers and is ignored by the computer.
- Deterministic: The opposite of random. A computer is deterministic because it always does exactly as it is told.