Sequential Statements
The first of the five, and the one you already use. A sequential statement is simply one that runs after the one above it — top to bottom, once each. There is no keyword to learn and nothing to type, because this is what Python does when you have not asked for anything else.
1A program to watch: the sum of two numbers
Four statements, and nothing in them you have not met. Read it first, then we will run it one line at a time.
a = 25
b = 17
total = a + b
print('Sum =', total)Sum = 42
Store 25. Store 17. Add them and store that. Show it. Four instructions, carried out in the order they are written, each exactly once — and then the program ends, because there is no line 5.
2Watch it run, one statement at a time
Python is only ever doing one line at a time. Step through it below and watch two things: what each statement leaves behind in memory, and how long the screen stays blank.
Step through sum.py and watch what each statement leaves behind.
a = 25b = 17total = a + b print('Sum =', total)nothing yet
still blank
Nothing has happened yet. Python is about to start at the top — memory is empty and the screen is blank.
Two things in that are worth saying out loud. First, nothing appeared on the screen until the last line. Three statements had already run and the output pane was still empty, because storing a value is not the same as showing it — only print() shows.
Second, each statement worked with what the ones above it left behind. By the time total = a + b ran, both a and b already existed, so it had something to add. That is not luck. It is the order.
3The order is the program
Statements are not a list of things to be done in any convenient order. Move one line and you have a different program — sometimes a broken one. Here is the same four statements with the last two swapped:
a = 25
b = 17
print('Sum =', total)
total = a + bTraceback (most recent call last):
File "out_of_order.py", line 4, in <module>
print('Sum =', total)
^^^^^
NameError: name 'total' is not definedEvery statement here is correct on its own. The program still fails, because at the moment print() ran, total had not been worked out yet — the line that creates it is sitting one line below, waiting its turn that will never come. You met this error in the Errors chapter; here is where it comes from.
marks = 40
print(marks)
marks = marks + 1040
No traceback, no complaint — it printed 40 because that is genuinely what marks held at that moment. The 10 was added afterwards, to nobody's benefit. This is a logical error, and misordered statements are one of the commonest ways to write one.
4Try it
Run it as it stands, then move the print() line up one and run it again. Then try adding a third number.
5Recap
In sum.py, when does anything appear on the screen?
a = 25 / b = 17 / print('Sum =', total) / total = a + b — what happens?
How many times does a sequential statement run?