2023-01-23
Since its first public release in 1991, Python has become one of the most widely used general-purpose programming languages. The popularity of Python may be explained by the following features:
In the lessons that follow, we will focus on three third-party modules for scientific, engineering, financial and mathematical computing:
This introductory lesson aims to make you familiar with two software applications for running and creating Python programs. By the end of the lesson, you should be able to
These lessons will ask you to try out numerous Python commands, and you should do so while reading.
The lessons aim to provide the minimum necessary information about the topics covered, but you can easily find more detailed resources on the internet and we provide suggestions for further reading at the end of each lesson.
If using your own computer, then you will need to install the Anaconda Distribution to access Spyder and Jupyter by following these instructions. The applications run on Linux, Windows and MacOS with minimal differences, so provided you are able to start Spyder and Jupyter you should be able to follow along regardless of your operating system.
Start the Anaconda Navigator application by clicking on the icon shown above or by typing ‘anaconda’ in your Desktop search facility. You should see a window like the screenshot below; be patient, the application can take a while to open.
Spyder is an integrated development environment or IDE for Python, designed specifically for programmers working in scientific and technical fields. In the Anaconda Navigator window, locate the Spyder card and click on the ‘Launch’ button. A window should open, looking like the screenshot below.
The left half of the window is taken up with the editor pane.
On the right are two panes. In the top pane you can select ‘Help’, ‘Variable Explorer’, ‘Plots’ and ‘Files’. In the screenshot, ‘Files’ is selected so a list of files is shown. Above the pane you can see the path to the folder containing the files. Clicking on the folder icon to the right of this path opens a dialogue that you can use to navigate to whichever folder you wish to access. Typically, selecting a folder in this way will be the first thing you do after starting Spyder.
The bottom pane on the right is an IPython console. IPython is a program that augments the basic Python shell with features that are useful for interactive use (hence the initial ‘I’ in the name). A shell is a simple, text-based environment in which, after you type a command and press Enter, the shell evaluates the command, prints any output, and then displays its prompt again. The IPython prompt looks like ‘In [n]:’ for a number n. An alternative term for shell is REPL, which stands for ‘Read-Evaluate-Print-Loop’.
From the ‘Help’ menu, select ‘About Spyder …’ to see which version of the software you have installed. You should see a pop-up window like the one below which shows the Spyder version is 5.3.1. If you are using another version then you might encounter some minor differences from the behaviour described here. Press ‘OK’ to close the pop-up window.
Try clicking in the IPython pane. You should see the cursor blink next to the ‘In [1]:’ prompt, indicating that the shell is ready for you to type a command. Type the following two lines (pressing Enter after each):
x = 2
y = x/2 + 1/x
The first statement creates a variable x and assigns it the value 2. The second statement creates a second variably y and assigns it the value of the expression x/2 + 1/x, which in this case equals 2/2 + 1/2 or in other words 1.5. If you type a variable name on a line by itself, then IPython will display the current value of that variable. Try typing y. Notice how IPython prefixed the output on the nth command with ‘Out[n]:’. Another way to see the value of a variable is to click on the ‘Variable Explorer’ tab in the top right pane.
Suppose that we meant to put y equal to x/2 + 3/x and typed the 1 by mistake. Instead of typing the whole line again, we can press the up arrow key to have IPython display previous lines. Try this now. You can also use the down arrow key to work through the command history in the opposite direction.
The instructions below assume that NumPy commands are available in the IPython shell. At the top right of the IPython pane, click on the icon consisting of three horizontal lines, then ‘Special consoles’ and finally ‘New Pylab console (data plotting)’. A new console will open and you should see the message ‘Populating the interactive namespace from numpy and matplotlib’.
You can change the default behaviour of Spyder by clicking on the ‘Tools’ menu and selecting ‘Preferences’. A popup window should appear. In the left sidebar, select IPython console and click on the ‘Graphics’ tab.
If you tick the checkbox to ‘Automatically load Pylab and NumPy modules’ followed by ‘OK’, then every time you start Spyder NumPy will be loaded into the IPython console.
Suppose that we want to find \(\sqrt{3}\). At the IPython prompt, type the following without pressing Enter.
sqrt(
You should see a pop-up message describing the sqrt function. (Don’t worry if the message does not make a lot of sense right now.) Alternatively, type
?sqrt
and press Enter. (When you are done with reading the help, press ‘q’ to quit and get back the IPython prompt.) This kind of help message about a function is called a docstring.
To actually calculate \(\sqrt{3}\), you just have to type
sqrt(3)
and IPython will print the result.
The names of most of the standard mathematical functions are easy to guess, e.g., exp, sin, cos and log. From its docstring, you can check that log returns the natural logarithm, whereas log2 and log10 give the logarithm to base 2 and base 10, respectively.
Download the file cubic.py and save it to a convenient folder. Make sure the same folder is selected in Spyder so that cubic.py appears in the ‘Files’ tab of the top right pane. There are several ways to open the file in the editor pane. You can click the ‘File’ menu and select ‘Open’, or you can click on the ‘open file’ icon towards the left of the main toolbar, or you can double-click on cubic.py in the list of files displayed in the ‘Files’ tab. Use one of these methods, and don’t worry for now about understanding the commands in the file.
The program in cubic.py plots the graph of the cubic polynomial \(x^3-2x+1\) for \(-2\le x\le 2\). To run the program, type the following command at the IPython prompt.
run cubic
To see the plot, you have to select the ‘Plots’ tab in the top right pane. This method works whether or not the file cubic.py is open in the editor. Alternatively, clicking the green ‘play’ icon in the toolbar will run whatever code is displayed in the current editor tab. Try both methods.
Exercise: download and run the file parabola.py.
To close Spyder, click on the ‘File’ menu and select ‘Quit’.
In the Anaconda Navigator window, locate the Jupyter Notebook card and click on the ‘Launch’ button. A window should open, looking something like the screenshot below, depending on your default web browser.
Navigate to the folder containing cubic.py and parabola.py by clicking on the folder links. Towards the top right of the page, click on the ‘New’ menu and select ‘Python 3’ to open an empty notebook. From the ‘Help’ menu, select ‘About’ to open at pop-up window like the one in the screenshot below, which shows that the version of the notebook server is 6.4.12. Press ‘OK’ to close the pop-up window.
Click on the box next to ‘In [1]:’ and type the same commands that we used earlier in Spyder:
x = 2
y = x/2 + 1/x
y
To execute these commands, you need to press Shift-Enter. The result should look like the following screenshot.
Notice how Jupyter creates a new cell, ready for you to type more commands. A notebook is simply a sequence of cells, that can contain either code or text. Click on the ‘Cell’ menu and select ‘Cell Type’ then ‘Markdown’. Notice that the ‘In []:’ disappears. Click in the cell, type ‘We will now plot a cubic polynomial’ and press Shift-Enter.
Go back to the first Jupyter tab and click on cubic.py to open the file in a Jupyter editor window. Use your mouse to copy the code and paste it in the empty code cell in your notebook tab. Press Shift-Enter to execute the commands. The plot should appear below the cell as in the next screenshot.
Notebooks are useful because you can easily combine Python code with text. Jupyter interprets the text cells as markdown, which provides many features for formatting, including
Try writing some text using these three formatting methods. You need to type Shift-Enter to see the rendered version of the markdown source.
Click on ‘Untitled’ at the top of the notebook tab and rename the notebook as ‘lesson_0’. From the ‘Cell’ menu, select ‘All Output’ and then ‘Clear’, to delete all of the output from the code cells. The notebook should autosave to a file lesson_0.ipynb. You can also click on the ‘Save and Checkpoint’ icon (looks like a floppy disk) or use the ‘File’ menu.
From the ‘File’ menu, select ‘Close and Halt’ to close the notebook tab. Close the editor tab by clicking on ‘Logout’, and finally from the initial Jupyter tab, click on ‘Quit’ followed by ‘Logout’. You should see a message saying ‘Successfully logged out’.
Spyder is designed for writing serious Python programs, whereas Jupyter is ideal for exposition about anything that depends on code in an essential way. For simple use cases, you can get by using either application. The IPython shell in Spyder is generally the most convenient way to experiment with Python commands, and your course might require you to complete some assessment tasks in a Jupyter notebook, so here we provide an introduction to both applications.
In this lesson you have seen how to
cubic.py;For more information about Spyder, click on the Spyder ‘Help’ menu and select ‘Spyder documentation’. The same menu has options for a ‘Tour’ and tutorials. Similarly, the ‘Help’ menu in a Jupyter notebook has options for a ‘User interface tour’ and ‘Keyboard Shortcuts’, as well as links to online documentation on ‘Notebook Help’ and ‘Markdown’. The menu also has links to the official (and very detailed) online documentation for Python, NumPy, SciPy and Matplotlib.