Simple Sequences

What will we cover?

A simple sequence of instructions is the most basic program you can write. The simplest sequence is one containing a single programme statement. A statement is usually entered all on one line, although occasionally they can spill over onto two or more lines. A statement is a group of words and symbols that is meaningful to the interpreter, it's a bit like a sentence in natural language. We will try out some of these now. The examples will show what you should type at the '>>> ' Python prompt, along with the result, and the following paragraph will explain what happens.

Displaying output

The first thing we need to learn is how to get Python to display some information. Without that we would not know what the computer had done and it would all be pretty pointless!

>>> print('Hello there!')
Hello there!

Note: 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. The part in bold is what you need to type, the second line is the output printed by the interpreter.

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() function 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. The characters must be inside parentheses, we'll discuss the significance of those later.

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...")
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:

Displaying Arithmetic Results

>>> 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. Python sees this as:

((6 * 5) + (7 - 5)) / (7 + 1)
=> (30 + 2) / 8
=> 32 / 8
=> 4

What happens if you type the same sequence without the parentheses?

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

This is because Python will evaluate the multiplication and division before the addition and subtraction. So Python sees it as:

(6*5) + 7 - (5/7)  + 1
=> 30 + 7 - 0.7143 + 1
=> 37 - 0.7143 + 1
=> 38 - 0.7143
=> 37.2857...

This is usually what you would expect mathematically speaking but it may not be what you expect as a programmer! Most 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 parentheses 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)

Which is pretty much what you would expect. But if you want to keep with whole numbers you can find the whole result and remainder by using the // sign like a division operator. Python will print the quotient:

>>> print(5//2)

And to get the remainder we use the modulo operator (%):

>>> print(5%2)
>>> print(7//4)
>>> print(7%4)

% is known as the modulo or mod operator and in other languages is often seen as MOD or similar. In fact in Python we can get both result (the quotient) and remainder (modulo) by using the divmod() function:

>>> print( divmod(7,4) )
(1, 3)

Experiment and you will soon get the idea. Why bother? Well, it turns out that so called integer arithmetic is very useful in programming. As a simple example we can tell whether a number is odd or even by dividing by two and checking whether the remainder was zero (i.e. it is even) or not (so it must be odd). Like this:

>>> print( 47 % 2 )

So we know 47 is odd. Now you could probably tell that just by looking at the last digit, 7. But imagine you were reading the data from a file or a user was typing it in. Then your program has to figure out whether it's odd or even by itself. You, the programmer, can't help it out by checking visually. That's one occasion when modulo (%) comes in very handy.

Mixing Strings and Numbers

>>> print( 'The total is: ', 23+45)
The total is:  68

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))
The sum of 7 and 18 is: 25

In this statement the format string contains '%' markers within it. These have nothing to do with the modulo operator we discussed above, instead they have a special meaning when used within a string like this. Unfortunately this double usage of % means you have to read carefully to determine the context and therefore what role the % is playing!

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 parenthesised expression following the % sign on its own. It is important that the number of values in the final parentheses matches the number of % markers inside the string. (If this all sounds a little confusing practice a few variations on the line above and with the information following and it will soon start to make sense.)

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

The Python documentation gives lots more...

In fact you can print any Python object with the print function. 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.

The string format method

The % style of string formatting has been superseded in Python v3 by an even more powerful (but more complex) style using the string format operation. The old style is still available and I will stick to that throughout the tutor but if you want to investigate the new approach check the documentation. Simple usage is not much different in principle from the old style, the example above would look like this:

  >>> print( "The sum of {:d} and {:d} is: {:d}".format(7,18,7+18)
The sum of 7 and 18 is: 25

The % markers are replaced with {} and the data type-codes are formatted slightly differently inside the markers. The other difference is that you have to call the format operation of the string passing the values as before. The new style has a bunch of other features though, both to enhance layout and the way the data can be passed in. I won't be covering that here but the documentation gives lots of examples. However, you may want to leave it until you have a few more topics under your belt because it is quite technical in its explanation.

Powering Up

>>> 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 functions and commands available to you called built-ins, because they are built in to the Python core. However Python can extend the list of functions available by incorporating extension modules. - It's a bit like buying a new tool in your favourite DIY store and adding it to your tool box. The tool is the sys part and the import operation puts it into the tool box.

In fact what this command does is makes available a whole bunch of new 'tools' in the shape of Python functions which are defined in a module called 'sys'. This is how Python is extended to do all sorts of clever things that are not built in to the basic system. In fact there are over a hundred modules in the standard library that you get with Python. You can even create your own modules and import and use them, just like the modules provided with Python when you installed it. We'll get to that later. There are also many more that you can download from the internet. In fact, any time you start a new project that is not covered by modules in the standard library, remember to do a Google search, there is probably something out there that can help you.

So how do we use these new tools?

A Quick exit

>>> sys.exit()

Whoops! What happened there? Simply that we executed the exit function defined in the sys module. That statement causes Python to exit.

Note 1: Normally you exit Python by typing the End Of File(EOF) character at the >>> prompt - CTRL-Z on Windows 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 parentheses 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 parentheses. 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 statements are actually only useful in combination. That is, to exit from Python other than by typing EOF you need to type:

>>> import sys
>>> sys.exit()

This is a sequence of two statements! 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("<br />");
document.write(  ((8 * 4) + (7 - 3)) / (2 + 4)  );
document.write("<br />");
document.write( 5/2 );
document.write("<br />");
document.write( 5 % 2 );

And the output should look like this:

We use document.write to output text into the browser window. That's roughly equivalent to Python's print function. We'll see a slightly different approach to browser output in the VBScript example below.

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 />.

Notice too that we had to escape the single quote characters by putting a \ sign in front of the quote. We will explain more about that when we discuss strings in the Raw Materials topic, coming up next.

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. (We could have done the same thing in the JavaScript example by using alert in place of VBScript's MsgBox. That is, we could have used alert("Hello There!") instead of document.write("Hello there!<br>") to produce lots of dialogs like we had in VBScript.)

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 character code. It's 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 character code for any character visiting this web site and looking up the decimal code. (All the popular operating systems provide a Character map desktop applet that will do the same job if you prefer.) As a last resort, use the following bit of JavaScript and replace the double quote character with whichever character you want:

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

Don't worry about what the numbers mean just yet, we'll get to it in the next topic but, for now, just use it should you be forced to find out a character's 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

Previous  Next