for loops#

Lesson materials#

Materials for this lesson can be found on the website for the Introduction to Python for Geographic Data Analysis book.

Student notebooks#

Students in the course can work through notebooks with limited code cell content by creating their copy of the notebooks from GitHub Classroom. Instructions for this can be found on the Exercise notebooks in GitHub Classroom page.

Exercise(s)#

Putting it together#

  • Create a new NumPy array called numbers that starts at 1 and goes to 100 in increments of 1

  • Create a new NumPy array of zeros called squared that is the same size as numbers

  • Using a for loop, calculate the square of each value in numbers and store it in the corresponding location in squared

# You can put your code for the exercise above in here :)

Let’s get functional#

  • Take your code above and use it to create a new Python function square() that accepts a NumPy array and returns an array of squared values

  • Do you get the expected results when using your function?

  • Can you break your function (get it to give an error message)? If so, how?

# Put your code for the exercise above in here

Drag race#

IPython has a magic function called %timeit that you can use in a Jupyter Notebook to calculate how long it takes a line of code (or program) to execute.

import numpy as np

%timeit np.ones(100000000).mean()
78.8 ms ± 274 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)

We can use this now to compare the performance of your new square() function with calculating the square of values directly in NumPy

  • Create a new NumPy array called input that goes from 1 to 10 in increments of 0.0000001

  • Use %timeit with your function above to calculate the square of input, storing the output in an array called out1

  • Compare the performance of your function to simply squaring the input array directly and storing its output as out2

  • Can you see any benefits to using NumPy?

# Put your code for the exercise above in here