# A simple script (with a descriptive comment)
print("Welcome to python !")
Python on the web
There are many different ways to run python code. For the simplest tasks, a web browser is all you need to edit and run simple tasks. In this introductory session, we will use a python interpreter embedded in each web page to learn the basic language itself.
You will find examples of python code such as this one which contains some Python code which you can copy but which you can’t run and you can’t edit. Note that the code is highlighted (coloured) by meaning.
We use these blocks to give you examples and fragments of code that you can use later. Other code blocks have a run
button and they can usually be edited (and, don’t worry, they can be reset if you make a mistake). We use these live code blocks for you to try things out. Give it a go (you can’t break anything).
Generally, we’ll use the live code blocks as part of an exercise for you to try something specific. The exercise blocks look like this:
We’ve already seen a couple of examples of Python code. Now let’s try making something from scratch. One thing we can do is simply use Python like a calculator!
Exercises with Solutions
In some cases, you can check your answers by running the code and comparing the output to the expected result. Here is a simple example in which you are asked to write some code to print the mean of the integers from 1 to 99.
Comments
In the examples above, you may have noticed the line
which doesn’t look as though it ought to be valid Python code. This is a ‘comment’ line: the computer ignores the
#
and anything following it on the same line. Comments should be used to document information that helps people to understand how the code works internally. This may seem like a waste of time - but you (or your colleagues) will be grateful in two years’ time when you find you need to change something! The comment character can also be useful for ‘switching off’ lines of code without deleting them. For example, look at this piece of code:The first three lines of comments provide information recording some of the assumptions the programmer made when writing this function (don’t worry if it doesn’t make sense yet!). The fourth comment line is a piece of code that has been ‘commented out’: we don’t want to routinely print the file header, but it is useful to be able to reinstate this easily in case we encounter problems and need to check what the function has read.
In fact, ‘commenting out’ code is so common that most editors provide a straightforward way to do it. If you select a block of code and press Ctrl+/ (or on a Mac, ⌘+/), the selected lines will all be changed to begin with
#
comment characters. Pressing Ctrl+/ again will restore the original version. Smart editors know how to do this for many different languages.