Scientific computing with Python

by Conor Lawless email: conor.lawless@ncl.ac.uk

Your first Python script

It's traditional, when learning a programming language, to use it to make your computer print "Hello World!". In achieving this you have to be able to write something which the interpreter can understand, that is something written in syntactically correct Python. You have to understand the format of a Python script, and how to execute one. So, to complete this simple task, we have to overcome a few hurdles.

Script format

A Python script is a text file with a .py extension. An easy way to create a script is to open a text editor (e.g. Notepad on Windows), write some Python text, save the file as "myscript.py", for example. Note that although this file is a text file, the extension must be ".py" to signify that the file's contents are written in the Python language. Also note that, using Notepad on Windows, it is necessary to include inverted commas around the filename, otherwise it will attempt to save the file with a .txt extension. Similarly, on Windows, depending on your settings, you might not even be able to see file extensions properly. To adjust this behaviour, you can follow these instructions.

Let's try that now, by copying the two coloured lines of text below into an empty text file, saving the file as "myscript.py".

# First script!
print("Hello World!")

There are several different ways to run this script, depending on what's most convenient, and we will learn about some of these on the next page.

Before we do that, let's look at an alternative text editor, the one which comes with the IDLE Python interpreter.

On your own, Windows based machine you can start the IDLE Python interpreter as follows:

Start -> All Programs -> Python 2.7 -> IDLE (Python GUI)

Newcastle's IT department have installed Python in an unusual location on machines in the Dene cluster, so if you are using one of those machines:

Start -> All Programs -> ARCGIS -> Python 2.7 -> IDLE (Python GUI)

This opens a live console (or shell) for executing Python commands. IDLE also provides a text editor, specifically designed to help with understanding and running code. With the Python shell open, go File -> New Window to start writing a new script. If you copy and paste the text above into this Untitled window, and save the file as "myscript.py" you will see that text automatically becomes coloured. The IDLE text editor colours text depending on whether a piece of text contains comments, strings etc. and later we will see that it helps with tasks like indenting text and ensuring sets of brackets are closed.

Save this script before we execute it. File -> Save As -> myscript.py


OverviewInstallationFirst ScriptExecutionLibrariesStructureOther Resources


Last updated: April 2013