Computational Guided Inquiry for Modeling Earth's Climate (Neshyba & Deloya Garcia, 2023)¶

Arrays¶

Overview¶

Python is a widely used, open source programming language developed by Guido van Rossum. It was first released in 1991. Python is a great language for beginner programmers because it was designed with the newcomer in mind, but it also has extensive mathematical and scientific libraries. And it's free!

Here, the goal is for you to get used to some of the basics of python usage: how to use it as a calculator, and how to generate and plot arrays of numbers.

Computing skills¶

  1. I can use python to print text, numbers, and the results of algebraic expressions.
  2. I can create arrays of numbers "from scratch" using linspace, and other arrays of numbers from them.
  3. I know how to use pyplot to make simple graphs with basic annotation.
  4. I can calculate numbers using "order of operations" rules.

Importing resources¶

Generally, you'll need to bring in the libraries for numerical operations and graphics. That's what the next two cells do. Click in the two boxes below, and press shift-enter to execute one after another.

In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [2]:
%matplotlib notebook

Printing to the screen¶

The purpose of the cell below is to get your program to output the phrase Hello, world! You can run this cell by pressing shift-enter, like before.

In [3]:
print("Hello, world!")
Hello, world!

Your turn¶

Use the cell below to output the statement "Python is cool!" (remember you need to put the text in quotation marks):

In [4]:
### BEGIN SOLUTION
print("Python is cool!")
### END SOLUTION
Python is cool!

Using Python as a calculator¶

Execute (i.e., press shift-enter) the cell below.

In [5]:
# Adding: 5 + 10
print(5 + 10) 
print(5 + 10.0) 
15
15.0

A few things to note about the cell above:

  1. We have used the pound symbol (#) at the top of the cell. This is used to indicate a comment. Comments are used to make it easier to read and understand, but they don't do anything.
  2. Python will output integers if you add or multiply integers, otherwise you're likely to get a floating point number (which is Python's equivalent of a real number).
  3. We've placed a space before and after the plus signs, but that's just cosmetic; we'd get the exact same answers if the spaces weren't there.

Raising to a power¶

We can also get exponents, although the syntax might be different than what you are used to: python uses double asterisks. Execute the cell below to get a feel for it.

In [6]:
# Double asterisks (*) are used to represent an exponent
print(2**2)

# Sometimes you'll need to put the exponent in parentheses
print(2**(1/2))
4
1.4142135623730951

Storing data as named variables¶

Python can also make use of named variables for computation. It's super handy! Execute the cell below and study the results.

In [7]:
x = 5
X = 10
N = 6.02e23
h = 6.6e-34
print(x)
print(X)
print('Avogadro = ', N)
print('Planck =', h)
5
10
Avogadro =  6.02e+23
Planck = 6.6e-34

OK, some things to note about this:

  • Variable names are case-sensitive (so "x" and "X" were different variables).
  • Once a variable is assigned a value, it'll keep that value until you change it -- this even carries over into different cells.
  • Some names should never be used for variables because Python has reserved them for special purposes. For example, you shouldn't enter things like "print = 5", because if you do, you won't be able to print anything to the screen!. You will know you have typed a reserved word because it will appear green in your Notebook.
  • Speaking of printing, you'll notice that you can print multiple things, as long as they're separated by commas.
  • Python accepts values in scientific notation (like 6.6e-34).

Three steps for refreshing and saving your code¶

It's good practice to, periodically, re-run the notebook up to here, from the beginning, refreshing all the variables:

  1. Use the dropdown menu Kernel/Restart
  2. Use the dropdown menu Cell/Run All Above

Try this now! Assuming all goes well, take this additional step:

  1. Under the "File" dropdown menu item in the upper left is a disk icon. Press it now to save your work (and do it again every few minutes!)

Order of operations¶

Python follows the standard order of operations that hand calculators and spreadsheets use: multiply and divide take precedence over adding and subtracting, and parentheses take precedence over that. For example, one of the results below will yield a different result from the others. Which one?

  • $a = 9 * 8^2 - 13$
  • $b = 9 * (8^2-13)$
  • $c = (9 * 8^2)-13$

Your turn¶

In the cell below, make three named variables ($a$, $b$, $c$) and assign them the expressions above.

In [8]:
### BEGIN SOLUTION
a = 9*8**2-13
b = 9*(8**2-13)
c = (9*8**2)-13
### END SOLUTION

# Print the results
print(a,b,c)
563 459 563

Scalars vs arrays¶

So far we have discussed variables having just a single value. These are called scalars. Often, however, we want to work with arrays of numbers. Numpy's linspace function is an easy way to set that up. In the example below, we create an array of twenty numbers, from -5 to +5, and store it as variable xarray.

In [9]:
# Create an array
xarray = np.linspace(-5,5,num=20)

# Print it
print(xarray)
[-5.         -4.47368421 -3.94736842 -3.42105263 -2.89473684 -2.36842105
 -1.84210526 -1.31578947 -0.78947368 -0.26315789  0.26315789  0.78947368
  1.31578947  1.84210526  2.36842105  2.89473684  3.42105263  3.94736842
  4.47368421  5.        ]

Your turn¶

Remake the x-array, but running from 0 to 2, with 50 values, and print it.

In [10]:
### BEGIN SOLUTION
xarray = np.linspace(0,2,num=50)
### END SOLUTION

# Print the results
print(xarray)
[0.         0.04081633 0.08163265 0.12244898 0.16326531 0.20408163
 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959
 0.48979592 0.53061224 0.57142857 0.6122449  0.65306122 0.69387755
 0.73469388 0.7755102  0.81632653 0.85714286 0.89795918 0.93877551
 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347
 1.2244898  1.26530612 1.30612245 1.34693878 1.3877551  1.42857143
 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939
 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735
 1.95918367 2.        ]

Making arrays from other arrays¶

Here's something cool: when you use an array in an algebraic expression, the resulting variable is also an array! The cell below calculates the array version of $x^2$, for example, and stores the result in a new variable called "xsquared".

In [11]:
xsquared = xarray**2
print(xsquared)
[0.00000000e+00 1.66597251e-03 6.66389005e-03 1.49937526e-02
 2.66555602e-02 4.16493128e-02 5.99750104e-02 8.16326531e-02
 1.06622241e-01 1.34943773e-01 1.66597251e-01 2.01582674e-01
 2.39900042e-01 2.81549354e-01 3.26530612e-01 3.74843815e-01
 4.26488963e-01 4.81466056e-01 5.39775094e-01 6.01416077e-01
 6.66389005e-01 7.34693878e-01 8.06330696e-01 8.81299459e-01
 9.59600167e-01 1.04123282e+00 1.12619742e+00 1.21449396e+00
 1.30612245e+00 1.40108288e+00 1.49937526e+00 1.60099958e+00
 1.70595585e+00 1.81424406e+00 1.92586422e+00 2.04081633e+00
 2.15910037e+00 2.28071637e+00 2.40566431e+00 2.53394419e+00
 2.66555602e+00 2.80049979e+00 2.93877551e+00 3.08038317e+00
 3.22532278e+00 3.37359434e+00 3.52519783e+00 3.68013328e+00
 3.83840067e+00 4.00000000e+00]

Your turn¶

In the cell below, make an array corresponding to $x^{1/2}$; name this new array "rootx".

In [12]:
### BEGIN SOLUTION
rootx = xarray**(1/2)
### END SOLUTION

# Print the results
print(rootx)
[0.         0.20203051 0.28571429 0.34992711 0.40406102 0.45175395
 0.49487166 0.53452248 0.57142857 0.60609153 0.63887656 0.67005939
 0.69985421 0.72843136 0.75592895 0.7824608  0.80812204 0.83299313
 0.85714286 0.88063057 0.9035079  0.9258201  0.94760708 0.96890428
 0.98974332 1.01015254 1.03015751 1.04978132 1.06904497 1.08796759
 1.10656667 1.12485827 1.14285714 1.16057691 1.17803018 1.19522861
 1.21218305 1.22890361 1.2453997  1.26168012 1.27775313 1.29362645
 1.30930734 1.32480264 1.34011879 1.35526185 1.37023758 1.38505139
 1.39970842 1.41421356]

Graphing¶

How about visualizing these relationships? The cell below shows how to do this with the arrays you've created. There's also some annotating -- the x- and y-axes are labeled, and we've added a grid.

In [13]:
# Initialize the plot window
plt.figure()

# Plot x^2 as a function of x
plt.plot(xarray,xsquared)

# Annotate the axes
plt.xlabel('x')
plt.ylabel('x^2')
plt.grid(True)

Your turn¶

In the cell below, plot $x^{1/2}$ as a function of x, and annotate like above.

In [14]:
# Initialize the plot window
### BEGIN SOLUTION
plt.figure()
### END SOLUTION

# Plot x^(1/2) as a function of x
### BEGIN SOLUTION
plt.plot(xarray,rootx)
### END SOLUTION

# Annotate the axes
### BEGIN SOLUTION
plt.xlabel('x')
plt.ylabel('x^.5')
plt.grid(True)
### END SOLUTION

One last refresh and save¶

We're at the end of the notebook. You should repeat the "Three steps for refreshing and saving your code" you did before. Instead of using the dropdown menu "Cell/Run All Above", however, you may as well use "Cell/Run All".

Validating¶

This step will help ensure that you didn't miss something (although it's not a guarantee). Find the "Validate" button and press it. If there are any errors or warnings, fix them.

Three steps for finishing up¶

Assuming all this has gone smoothly, there will be three more steps (but read this carefully before carrying them out):

  1. Close this notebook using the "File/Close and Halt" dropdown menu
  2. Using the Assignments tab, submit this notebook
  3. Press the Logout tab of the Home Page