|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.
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.
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...
It's not just characters that can be printed:
>>> print(6 + 5) 11
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) ) 4.0
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) 37.2857142857
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) 2.5
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) 2
And to get the remainder we use the modulo operator (%):
>>> print(5%2) 1 >>> print(7//4) 1 >>> print(7%4) 3
% 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 ) 1
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.
>>> 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... Note however that this style of formatting has been replaced in Python v3 by an even more powerful (but more complex) style which we will discuss in more detail when we get to the Handling Text topic later.
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.
>>> 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?
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 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 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...
And the output should look like this:
<html><body> <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 </script> </body></html>
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. 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" </script>
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|
Previous  Next  Contents
If you have any questions or feedback on this page send me mail at: firstname.lastname@example.org