Python Introductory lab#
Directions: Follow the instructions on this worksheet and write your answers as you go along. If you have any trouble, check to be sure you followed the instructions. If you still need assistance, ask an instructor during the timetabled exercise session.
Aim: This practical assumes no prior Python knowledge. By following the steps below, you’ll learn how to access Python, how to load some simple *.nc
files, and carry out basic calculations.
Learning outcomes: At the end of this lab, you will be able to:
Create variables in Python from numbers, i.e. simple scalars, vectors and matrices, so that you can perform calculations on the variables after.
Perform simple averages of the data and arithmetic operations, using functions
mean
,median
,sin
, operators-
,*
, and**
Use commands
help
andprint
andtype
to investigate functions and variables.
Start a new code cell.#
In a jupyter notebook, you use the plus
or ‘+’ symbol which can be found along the top bar of this window. Alternatively, within each cell (block of code or text), there is a little bar with a + over or under it. This will add a cell above or below the current cell.
Arithmetic in Python#
Python can carry out all basic kinds of arithmetic. Most of the operators are the same as you’d expect. Try typing the following mathematical expressions in your code cell. Press “shift+Enter” or click the “>” play button along the top bar, and Python will evaluate or carry out your command.
a. Try the following in your code cell above.
3+5*2
b. Recall order of operations for arithmetic. It applies here as well.
(3+5)*2
c. Fractions or division
3/5
d. Raise numbers to powers (i.e. squaring numbers)
5**2
For each of the lines above, if you entered more than one in a single cell and then ran or executed the cell, which output was printed to the screen?#
Create a variable in Python. One of the powerful things about programming languages is that you can “name” your data. Rather than carrying out a stream of calculations in the command window, you can work with different numbers at the same time, save partial answers, and combine them later.
a. Create a scalar variable. To create a variable, you choose a name for it which starts with a character, e.g.
a
, and then put it at the left of the equal sign in your command window. Put the value you’d like to assign to that variable to the right of the equal sign. A scalar variable is a single number.a=3
Enter this in a code cell below.
Create a new code cell after, and type
a
then run the cell. What is printed to the screen?Try also a
print(a)
then execute. This shows you what is contained in your variablea
.Try a
type(a)
then execute. This command tells you what type of variablea
is.
# Your code here
a=3
b. Lists. Create a list. In Python, we can string together a set of numbers (or anything else) with square brackets and commas into a “list”.
x=[1, 2, 3]
c. Try a print(x)
and type(x)
.
d. How long is your vector? Try len(x)
.
x=[1,2,3]
print(x)
[1, 2, 3]
Numeric operations + packages#
Now we’d like to do some more numeric operations. Basic python has a lot of functionality, but to add additional capabilities, we import “packages”. The packages must be installed on the computer or system already (see installation instructions), but in order for your python notebook to know about those capabilities, you need to import
the packages.
A common package for numeric operations is numpy
. To import this package, we use the command import
and then the package name, numpy
. Then to call operations from the package, we would use the commands from within numpy
by writing numpy.COMMAND
. Some packages (like numpy
) are so commonly used that we get lazy to write numpy
all the time, and we want to shorten it. We do this by renaming the package as we import it.
import numpy as np
Typically, the cell importing packages is at the top or near the top of your notebook, so for all future notebooks in this course, the first code cell will be the import cell.
# Now we'd like to do some more numeric calculations
import numpy as np
With numpy, we also have access to basic functions and irrational numbers.
e. Irrational numbers
np.pi
f. Trigonometric functions. Try to calculate \(\sin(\pi)\).
np.sin(pi)
will produce an error message. Can you use the error message to fix the command?
Note: that due to machine or numeric precision, this may not be exact.
g. More functions. How about \(\log_{10}(10)\)?
# Your code here
Useful reference#
https://numpy.org/doc/stable/user/basics.creation.html
# Create a numpy array
x1D = np.array([1, 2, 3, 4])
# Print the contents of the new array to the screen using the `print` command
# Check the type of the array with the `type` command
Check for yourself - how did these differ from the list x
above?#
Calculate the average of the vector#
Here, there are two different ways to do this. Type the numpy
command mean
with “np.mean(
np.mean(x1D)
Try this below.
In another cell after, the alternate formulation is:
x1D.mean()
np.mean(x1D)
2.5
x1D.mean()
2.5
Now try creating a 2 dimensional array (matrix)#
a2D = np.array([[1, 2], [3, 4]])
Calculate the mean of the rows.
Want to find out more about how to use a function in python? There are three ways. Try them below
help(np.mean)
or “np.mean?”
Use the information in the function help file to figure out how to calculate the mean of the rows. (Look for the axis
option.)
np.mean?