08: Sequence in Python

The Theory:

Plan the order of instructions carefully
Sequence in python: Plan the order of instructions carefully

When a toddler learns to get dressed, they’re learning a sequence of instructions. They know that they need to put on both their pants and trousers. If they get the order right, they’ll look nice and smart. If they get the order wrong they’ll look like a superhero. 

Getting the order wrong with instructions in your code doesn’t always lead to such a fun result, so planning out the sequence of instructions clearly in your head (or on paper) can save a lot of time and frustration.

There are some hints to help you with the sequence of instructions in code:

  1. Set before you get 

    If you’re trying to get the data stored in a variable, your code should have already set something to be stored in that variable.

    It’s a good idea to set your variables to sensible initial values early on in your code.

  2. Split your sequences into sections

    Some people like to show off by writing long complicated lines of code that do all sorts of clever things all in one go. There’s nothing wrong with that if it works but your code will be much easier to read and you’ll be much less likely to make mistakes if you keep things as simple as possible.

    It helps to split complex calculations into a sequence of smaller, easier to understand calculations over several lines of code.

    Adding empty lines between sections of code that do different tasks and commenting each ‘paragraph’ of code lets you describe each sequence so you’re less likely to make mistakes.

  3. Talk before you type

    If you’ve got a complex problem to solve and you’re not sure where to start, start by explaining what you need your program to do. Even if you end up talking to yourself (some people use plastic rubber ducks!): the process of talking through (or scribbling down) the problem can help you see the sequence which, in turn,  shows you where to start.

Generally speaking, python will start at the top of a file and run each line in turn, unless it jumps to call procedures or functions that you’ve defined elsewhere in your code.

On the next page you’ll get some code examples that you can try out for yourself.

One thought on “08: Sequence in Python

Leave a Reply