More Sequences and Other Things

What will we cover?

OK, Now we know how to type simple, single entry, commands into Python and have started to consider data and what we can do with it. In doing so we typed in a few longer sequences of 5-10 lines. We are getting close to being able to write really quite useful programs but with one big snag: every time we exit Python we lose our programs. If you have been doing the VBScript or JavaScript examples you will see that you have stored those examples in files and so can run them repeatedly, we need to do the same with Python. I already mentioned that we can do this using any text editor, like notepad or pico, say, and saving the file with a .py file extension. You can then run the file from the operating system command prompt by prefixing the script name with python. Here is an example that uses a sequence of python commands; all things we've seen already:

#  File:
print( "hello world" )
print( "Here are the ten numbers from 0 to 9\n0 1 2 3 4 5 6 7 8 9" )
print( "I'm done!" )
# end of file

Note that the lines at top and bottom are not really needed, they are called comments and we will discuss them later in this topic. I added them to show more clearly what goes into the file. You can use Notepad or any other text editor to create the file so long as it saves in plain text. (ie. Don't use a word processor like MS Word since they save in a special binary format which python can't understand or use html which contains lots of formatting text, which again, means nothing to python.)

Now to run this program start up an operating system command prompt. (If you aren't sure about how to do that then see the box in the Getting Started topic.) Change into the directory where you saved your python file and execute it by prefixing its name with python, like this:

D:\PROJECTS\Python> python
hello world
Here are the ten numbers from 0 to 9
0 1 2 3 4 5 6 7 8 9 
I'm done!


You can see the Windows command prompt and the command I typed (in bold), plus the output of the program displayed before the command prompt reappears.

However, there is an easier way...

You might find that you have more than one version of Python installed on your computer (for example if your OS uses Python v2 for some tasks). In that case typing python may run the wrong version of Python and could result in unexpected errors. In that case simply append the version number of python you want to use onto the name. So for Python v3 you would type:

    D:\PROJECTS\Python> python3

Notice, it's now python3 rather than just plain python. That should be enough to fix things on most systems.

The joy of being IDLE

When you installed Python you also installed a useful application, itself written in Python, called IDLE. IDLE is what is known as an Integrated Development Environment, that is to say it includes several tools that help the programmer, all wrapped up in a single application. I won't be looking at IDLE in depth here, but the two features that I want to highlight are the fact that it provides an enhanced version of the Python >>> prompt, complete with syntax highlighting (That is, displaying different features of the language in different colours) and other nice features, plus a nice, Python specific, text editor which allows you to run your program files (such as the one we created above) directly from within IDLE.

I strongly recommend that, if you haven't already done so, you give IDLE a try. The best place to start, once you find the right way to start IDLE on your Operating System, is to visit Danny Yoo's excellent tutorial.

If you are using MS Windows there is yet another option in the form of PythonWin which you can download as part of the PyWin32 package. This gives access to all the Windows MFC low level programming functions and importantly, a very good alternative to IDLE. Pythonwin only works in Windows but is, in my opinion, slightly superior to IDLE. (If you happened to download python from the ActiveState web site their version includes all the PyWin32 features, including Pythonwin, as standard.) On the other hand IDLE is standard with Python so more people tend to use it and it works on most platforms. Whichever you choose it is a lot better than notepad, and it's always nice to be given a choice!

Finally, if you prefer a simple approach, you can find several text editors that support programming in Python in various ways. The vim editor provides syntax highlighting (colouring of key words etc), emacs has a full editing mode for Python and Scite is a very lightweight editor that provides Python syntax highlighting and other nice features.

If you go down the text editor route you will likely find it most convenient to have three windows open on your screen at once:

  1. The editor where you type in and save your source code
  2. A Python session where you try things out at the >>> prompt before adding them to your program in the editor and
  3. An operating system command prompt used to run the program to test it.

I personally prefer the 3 window approach, but most beginners seem to prefer the all-in-one style of an IDE like IDLE. The choice is entirely up to you.

If you are using JavaScript or VBScript I recommend using one of the editors mentioned above and a suitable web browser, say Chrome or Firefox (for VBScript that means Internet Explorer only - not Edge!), opened at the file you are working on. To test changes just hit the Reload button in the browser.

A quick comment

One of the most important of programming tools is one that beginners often feel is useless on first acquaintance - comments. Comments are just lines in the program which describe what's going on. They have no effect whatsoever on how the program operates, they are purely decorative. They do, however, have an important role to play - they tell the programmer what's going on and more importantly why. This is especially important if the programmer reading the code isn't the one who wrote it, or, it's a long time since he/she wrote it. Once you've been programming for a while you'll really appreciate good comments. I have actually been adding comments to some of the code fragments that you've seen already, they were the green bits of the lines with a # (Python) or ' (VBScript) symbol in front of them. From now on I'll be commenting the code fragments that I write. Gradually the amount of explanatory text will diminish as the explanation appears in comments instead.

Every language has a way of indicating comments. In VBScript it's REM (for Remark) or, more commonly, a single quote ' at the beginning of a comment. Everything after the marker is ignored:

REM This never gets displayed
' neither does this
msgBox "This gets displayed"

Note that the use of a single quote as a comment marker is the reason you can't start a string with a single quote in VBScript - VBScript thinks it's a comment!

Python uses a # symbol as its comment marker. Anything following a # is ignored:

v = 12     # give v the value 12
x = v*v    # x is v squared

Incidentally this is very bad commenting style. Your comment should not merely state what the code does - we can see that for ourselves! It should explain why it's doing it:

v = 3600    # 3600 is num of secs in an hour
s = t*3600  # t holds elapsed time in hours, so convert to secs

These are much more helpful comments.

Finally JavaScript uses a double slash: // as a comment marker. Once again, everything after the marker gets ignored.

Some languages allow multi-line comments between a pair of markers, but this can lead to some obscure faults if the terminating marker is not correctly input. JavaScript allows multi-line comments by using the pair of markers: /* followed by */, like this:

<script type="text/javascript">
document.write("This gets printed\n");

// A single line comment

/* Here is a multi line comment. It continues from this line
down into this line and even
onto this third line. It does not appear in the script output.
It is terminated by a reversal of the opening marker: */

document.write("And this prints too");

The important point about comments is that they are there to explain the code to anyone who tries to read it. With that in mind you should explain any mysterious sections - such as apparently arbitrary values used, or complex arithmetic formulae etc. And remember, the puzzled reader might be yourself in a few weeks or months time!

Sequences using variables

We introduced the concept of variables in the Raw Materials topic topic. There we said they were labels with which we marked our data for future reference. We saw some examples of using variables too in the various list and address book examples. However variables are so fundamentally important in programming that I want to do a quick recap of how we use variables before moving onto new things.

Now, at a Python Prompt(>>>), either in IDLE's Shell or in a DOS or Unix command window, try typing this:

>>> v = 7
>>> w = 18
>>> x = v + w    # use our variables in a calculation
>>> print( x )

What's happening here is that we are creating variables ( v, w, x ) and manipulating them. It's rather like using the M button on your pocket calculator to store a result for later use.

We can make this prettier by using a format string to print the result:

>>> print( "The sum of %d and %d is: %d" % (v,w,x) )

One advantage of format strings is that we can store them in variables too:

>>> s = "The sum of %d and %d is: %d"
>>> print( s % (v,w,x) )   # useful if printing same output with different values

This makes the print statement much shorter, especially when it contains many values. However it also makes it more cryptic so you have to use your judgment to decide whether very long lines are more or less readable than a stored format value. If you keep the format string beside the print statement, as we did here, then it's not too bad. Finally one other thing that helps is to name your variables in such a way that they explain what they are used for. For example instead of calling the format string s I could have called it sumFormat, so that the code looked like this:

>>> sumFormat = "The sum of %d and %d is: %d"
>>> print( sumFormat % (v,w,x) )   # useful if printing same output with different values

Now, in a program with several different format strings in use, we could more easily tell which format is being printed. Meaningful variable names are always a good idea and I'll try to use meaningful names where possible. Up until now our variables haven't had much meaning to convey!

Order matters

By now you might be thinking that this sequence construct is a bit over-rated and obvious. You would be right in so far as it's fairly obvious, but it's not quite as simple as it might seem. There can be hidden traps. Consider the case where you want to 'promote' all the headings in an HTML document up a level:

Now in HTML the headings are indicated by surrounding the text with
<h1>text</h1> for level 1 headings,
<h2>text</h2> for level 2 headings,
<h3>text</h3> for level 3 headings and so on.

The problem is that by the time you get to level 5 headings the heading text is often smaller than the body text, which looks odd. Thus you might decide to promote all headings up one level. It's fairly easy to do that with a simple string substitution in a text editor, substitute '<h2' with '<h1' and '</h2' with '</h1' and so on.

Consider though what happens if you start with the highest numbers - say h4 -> h3, then do h3 -> h2 and finally h2 -> h1. All of the headings will have moved to h1! Thus the order of the sequence of actions is important. The same is just as true if we wrote a program to do the substitution (which we might well want to do, since promoting headings may be a task we do regularly).

We've seen several other examples using variables and sequences in the Raw Materials topic - particularly the various address book examples. Why not think up a few examples for yourself? Once you've done that we'll move on to a new case study that we will build upon as we move through the tutorial, improving it with each new technique we learn.

A Multiplication Table

I'm now going to introduce a programming exercise that we will develop over the next few topics. The solutions will gradually improve as we learn new techniques.

Recall that we can type long strings by enclosing them in triple quotes? Let's use that to construct a multiplication table:

>>> s = """
1 x 12 = %d
2 x 12 = %d
3 x 12 = %d
4 x 12 = %d
"""   # be careful - you can't put comments inside 
>>>   # strings, they'll  become part of the string!
>>> print( s % (12, 2*12, 3*12, 4*12) )

By extending that we could print out the full 12 times table from 1 to 12. But is there a better way? The answer is yes, let's see what it is.

Points to remember

Previous  Next