Simple Sequences

What will we cover?
  • Single commands
  • The use of Python as a calculator
  • Using parentheses to get the correct result
  • Using format strings to print complex output
  • How to quit Python from within a program.

A simple sequence of instructions is the most basic program you can write. The simplest sequence is one containing a single command. We will try out some of these now. The heading will describe what you should type at the '>>> ' Python prompt, the following paragraph will explain what happens.

>>> print 'Hello there!'

The first thing to notice is that you don't need to type the space between the >>> and the 'print' - Python puts that there for you. Secondly Python cares about details like whether or not you use upper or lower case. If you typed Print instead of print you would get an error because Python considers the two words to be different. (JavaScript is also fussy about case whereas VBScript is much more forgiving, but it's best to just get used to being very careful about case when programming.)

The print command is the way to get Python to display its results to you. In this case it is printing the sequence of characters H,e,l,l,o, ,t,h,e,r,e,!. Such a sequence of characters is known in programming circles as a string of characters or a character string or just a plain string.

You signify a string by surrounding it in quotes. In Python you can use either single quotes (as above) or double quotes: "a string". This allows you to include one type of quote within a string which is surrounded by the other type - useful for apostrophes:

>>> print "Monty Python's Flying Circus has a ' within it..."

JavaScript and VBScript are both a bit more fussy about which types of quotes you can use and where. In both of those languages I recommend sticking to double quotes where possible.

It's not just characters that can be printed:

>>>print 6 + 5

Here we have printed the result of an arithmetic operation - we added six and five. Python recognized the numbers as such and the plus sign and did the sum for us. It then printed the result.

So straight away you have a use for Python: it's a handy 'pocket calculator'! Try a few more calculations. Use some other arithmetic operators:

We can combine multiple expressions like this:

>>> print ((6 * 5) + (7 - 5)) / (7 + 1)

Notice the way I used parentheses to group the numbers together. What happens if you type the same sequence without the parentheses? This is because Python will evaluate the multiplication and division before the addition and subtraction. This is usually what you would expect mathematically speaking but it may not be what you expect as a programmer! All programming languages have rules to determine the sequence of evaluation of operations and this is known as operator precedence. You will need to look at the reference documentation for each language to see how it works. With Python it's usually what logic and intuition would suggest, but occasionally it won't be...

As a general rule it's safest to include the brackets to make sure you get what you want when dealing with long series of sums like this.

One other thing to note:

>>> print 5/2

results in a whole number (integer) result (i.e. 2). This is because Python sees that the numbers are whole numbers and assumes you want to keep them that way. If you want decimal fractions as a result simply write one number as a decimal:

>>> print 5/2.0
Python sees the 2.0 and realizes that we are happy dealing with fractions (referred to as real numbers or floating point in computing parlance), so it responds with a fractional result. In the most recent versions of Python you can change this behavior to always produce real numbers from a division by adding this line to the top of your program:
>>> from __future__ import division

(Note, that's two underscores on each side of future)

Its likely that this will be the standard type of division in some future version of Python but for now you have to specifically tell Python that you want it turned on.

If you want to keep with whole numbers you can find the remainder by using the % sign like a division operator. Python will print the remainder:

>>> print 7/2
>>> print 7%2
>>> print 7%4

% is known as the modulo or mod operator and in other languages is often seen as MOD or similar.

Experiment and you will soon get the idea.

>>>print 'The total is: ', 23+45

You've seen that we can print strings and numbers. Now we combine the two in one print statement, separating them with a comma. We can extend this feature by combining it with a useful Python trick for outputting data called a format string:

>>> print "The sum of %d and %d is: %d" % (7,18,7+18)

In this command the format string contains '%' markers within it. The letter 'd' after the % tells Python that a 'decimal number' should be placed there. The values to fill in the markers are obtained from the values inside the bracketed expression following the % sign on its own.

There are other letters that can be placed after the % markers. Some of these include:

The Python documentation will give lots more...

In fact you can print any Python object with the print command. Sometimes the result will not be what you hoped for (perhaps just a description of what kind of object it is) but you can always print it.

>>>import sys

Now this is a strange one. If you've tried it you'll see that it apparently does nothing. But that's not really true. To understand what happened we need to look at the architecture of Python (for non Python programmers, bear with me there will be a similar mechanism available to you too!)

When you start Python there are a bunch of commands available to you called built-ins, because they are built in to the Python core. However Python can extend the list of commands available by incorporating extension modules. - It's a bit like buying a new tool in your favourite DIY shop and adding it to your toolbox. The tool is the sys part and the import operation puts it into the toolbox.

In fact what this command does is makes available a whole bunch of new 'tools' in the shape of Python commands which are defined in a file called ''. This is how Python is extended to do all sorts of clever things that are not built in to the basic system. You can even create your own modules and import and use them, just like the modules provided with Python when you installed it.

So how do we use these new tools?


Whoops! What happened there? Simply that we executed the exit command defined in the sys module. That command causes Python to exit.
(Note 1: Normally you exit Python by typing the End Of File(EOF) character at the >>> prompt - CTRL-Z on DOS or CTRL-D on Unix. In a development tool you exit using the File->Exit menu etc as usual.)
(Note 2: If you try this inside a development tool like IDLE the tool will probably catch the attempt to exit and display a message saying something about SystemExit. Don't worry that means the program is working and the tool is just saving you the bother of restarting from scratch.)

Notice that exit had 2 brackets after it. That's because exit is a function defined in sys and when we call a Python function we need to supply the parentheses even if there's nothing inside them!

Try typing sys.exit without the brackets. Python responds by telling you that exit is a function rather than by executing it!

One final thing to notice is that the last two commands are actually only useful in combination. That is, to exit from Python other than by typing EOF you need to type:

import sys

This is a sequence of two commands! Now we're getting closer to real programming....

Using JavaScript

Unfortunately in JavaScript there is no easy way to type the commands in and see them being executed immediately as we have been doing with Python. However we can type all of the simple commands we used above into a single HTML file and load it into a browser. That way we will see what they look like in JavaScript:

<script type="text/javascript">
document.write('Hello there!<BR>');
document.write("Monty Python\'s Flying Circus has a \' within it<BR>");
document.write(  ((8 * 4) + (7 - 3)) / (2 + 4)  );
document.write( 5/2 );
document.write( 5 % 2 );

And the output should look like this:

Notice that we had to write <BR> to force a new line. That's because JavaScript writes its output as HTML and HTML wraps lines into as wide a line as your browser window will allow. To force a line break we have to use the HTML symbol for a new line which is <BR>.

And VBScript too...

Like JavaScript we have to create a file with our VBScript commands and open it in a browser. The commands that we have seen, written in VBScript look like this:

<script type="text/vbscript">
MsgBox "Hello There!"
MsgBox "Monty Python's Flying Circus has a ' in it"
MsgBox 6 + 5
MsgBox ((8 * 4) + (7 - 3)) / (2 + 4)
MsgBox 5/2
MsgBox 5 MOD 2

And the output should consist of lots of dialog boxes each presenting the output from one line of the program.

One point to note is that you cannot start a string using a single quote in VBScript (We'll see why in a later topic) although you can include single quotes inside double quoted strings. To include a double quote inside a double quoted string we have to use a function called Chr which returns the character for a given ASCII character code. I'ts all very messy but an example should show how it works:

<script type="text/vbscript">
Dim qt
qt = Chr(34)
MsgBox qt & "Go Away!" & qt & " he cried"

Note that you can find out the ASCII code for any character by using the Character Map applet in Windows, or by visiting this web site and looking up the decimal value or, as a last resort, by using the following bit of JavaScript(!) and replacing the double quote character with the character you want:

<script type="text/javascript">
var code, chr = '"'; // put the character of interest here
code = chr.charCodeAt(0);
document.write("<BR>The ASCII code of  " + chr + "  is " + code);

Don't worry about what it means just yet, we'll get to it eventually for now just use it should you be forced to find out an ASCII value.

That's our first look at programming, it wasn't too painful was it? Before we continue though we need to take a look at the raw materials of programming, namely data and what we can do with it.

Points to remember
  • Even a single command is a program
  • Python does math almost the way you'd expect
  • To get a fractional result you must use a fractional number
  • You can combine text and numbers using the % format operator
  • Quit with import sys; sys.exit()

Previous  Next  Contents

If you have any questions or feedback on this page send me mail at: