{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# for loops\n", "\n", "## Sources\n", "This lesson is based on the [Software Carpentry group's](http://software-carpentry.org) lessons on [Programming with Python](http://swcarpentry.github.io/python-novice-inflammation/).\n", "\n", "## Basics of for loops\n", "\n", "### Introducing loops\n", "\n", "Loops allow parts of code to be repeated over some number of times.\n", "One of the simple loop options in Python is the `for` loop." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "word = 'rock'\n", "for char in word:\n", " print(char)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### for loop format\n", "\n", "`for` loops in Python have the general form below.\n", "\n", "```python\n", "for variable in collection:\n", " do things with variable\n", "```\n", "\n", "The `variable` can have any name you like, and the statement of the `for` loop must end with a ``:``.\n", "The code that should be executed as part of the loop must be indented beneath the `for` loop, and the typical indentation is 4 spaces.\n", "There is not additional special word needed to end the loop, just change the indentation back to normal.\n", "\n", "### Another loop example\n", "\n", "Let's consider another example." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "length = 0\n", "for letter in 'earthquake':\n", " length = length + 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('There are', length, 'letters')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the variable used in the loop, `letter` is just a normal variable and still exists after the loop has completed with the final value given to letter." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('After the loop, letter is', letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### for loops and the range() function\n", "\n", "A loop can be used to iterate over any list of values in Python.\n", "So far we have considered only character strings, but we could also write a loop that performs a calculation a specified number of times." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for number in range(5):\n", " print(number)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What happens here?\n", "Well, in this case, we use a special function called `range()` to give us a list of 5 numbers `[0, 1, 2, 3, 4]` and then print each number in the list to the screen.\n", "When given an integer (whole number) as an argument, `range()` will produce a list of numbers with a length equal to the specified number.\n", "The list starts at zero and ends with `number-1`.\n", "\n", "### Loops and index values\n", "\n", "Often when you use `for` loops, you are looping over the values in a list and either calculating a new value or modifying the existing values.\n", "Let's consider an example." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myList = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]\n", "print(myList)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(6):\n", " myList[i] = myList[i] + i\n", "print(myList)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, what happened?\n", "We first create a list of 6 numbers.\n", "Then, we loop over 6 values using the `range()` function and add each value to the existing location in `myList`.\n", "\n", "### The len() function\n", "\n", "One of the drawbacks in the example above is that we need to know the length of the list before running that `for` loop example.\n", "However, we already know how to find the length of a list using the `len()` function, and we can take advantage of this knowledge to make our `for` loop more flexible." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(len(myList)):\n", " myList[i] = myList[i] + i\n", "print(myList)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the `len()` function with `range()` to perform calcluations using list or array values is an *extremely* common operation in Python.\n", "\n", "### Exercise - Putting it together\n", "- Create a new NumPy array called `numbers` that starts at 1 and goes to 100 in increments of 1\n", "- Create a new NumPy array of zeros called `squared` that is the same size as `numbers`\n", "- Using a `for` loop, calculate the square of each value in `numbers` and store it in the corresponding location in `squared`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can put your code for the exercise above in here :)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise - Let's get functional\n", "- 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\n", "- Do you get the expected results when using your function?\n", "- Can you break your function (get it to give an error message)? If so, how?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Put your code for the exercise above in here\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise - Drag race\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "%timeit np.ones(100000000).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use this now to compare the performance of your new `square()` function with calculating the square of values directly in NumPy\n", "\n", "- Create a new NumPy array called `input` that goes from 1 to 10 in increments of 0.0000001\n", "- Use `%timeit` with your function above to calculate the square of `input`, storing the output in an array called `out1`\n", "- Compare the performance of your function to simply squaring the `input` array directly and storing its output as `out2`\n", "- Can you see any benefits to using NumPy?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Put your code for the exercise above in here\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 2 }