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
numbersthat starts at 1 and goes to 100 in increments of 1Create a new NumPy array of zeros called
squaredthat is the same size asnumbersUsing a
forloop, calculate the square of each value innumbersand store it in the corresponding location insquared
# 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 valuesDo 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.6 ms ± 202 μ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
inputthat goes from 1 to 10 in increments of 0.0000001Use
%timeitwith your function above to calculate the square ofinput, storing the output in an array calledout1Compare the performance of your function to simply squaring the
inputarray directly and storing its output asout2Can you see any benefits to using NumPy?
# Put your code for the exercise above in here