{ "cells": [ { "cell_type": "markdown", "metadata": { "cell_tags": [] }, "source": [ "## Repeat a block of code" ] }, { "cell_type": "markdown", "metadata": { "cell_tags": [ "objectives" ] }, "source": [ "#### Objectives\n", "\n", "* Explain what a for loop does.\n", "* Correctly write for loops to repeat simple calculations.\n", "* Trace changes to a loop variable as the loop runs.\n", "* Trace changes to other variables as they are updated by a for loop.\n", "* Explain what a list is.\n", "* Create and index lists of simple values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": { "cell_tags": [] }, "source": [ "### Lists" ] }, { "cell_type": "markdown", "metadata": { "cell_tags": [] }, "source": [ "We create a list by putting values inside square brackets:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cell_tags": [], "collapsed": false }, "outputs": [], "source": [ "names = ['Alice', 'Bob', 'Carl']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(names)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "names.append('Dave')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "names" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "names[:2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "names[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(names)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"Printing a name: \" + names[0])\n", "print(\"Printing a name: \" + names[1])\n", "print(\"Printing a name: \" + names[2])\n", "print(\"Printing a name: \" + names[3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cell_tags": [], "collapsed": false }, "outputs": [], "source": [ "for n in names:\n", " print(\"Printing a name: \" + n)" ] }, { "cell_type": "markdown", "metadata": { "cell_tags": [] }, "source": [ "### For Loops" ] }, { "cell_type": "markdown", "metadata": { "cell_tags": [] }, "source": [ "A [for loop](../../gloss.html#for-loop)\n", "to repeat an operation---in this case, printing---once for each thing in a collection.\n", "The general form of a loop is:\n", "\n", "
\n",
"for variable in collection:\n",
" do things with variable\n",
""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cell_tags": [],
"collapsed": false
},
"outputs": [],
"source": [
"names.reverse()\n",
"print(names)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"len(names)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"len(names[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Challenge"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a cell in the notebook that computes the sum of the number of characters of each string in the names list"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tot = 0\n",
"for name in names:\n",
" tot = tot + len(name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(tot)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def compute_total_characters(names):\n",
" tot = 0\n",
" for name in names:\n",
" tot = tot + len(name)\n",
" return tot"
]
},
{
"cell_type": "markdown",
"metadata": {
"cell_tags": []
},
"source": [
"### Testing"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"assert compute_total_characters([]) == 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"assert compute_total_characters([\"a\"]) == 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"assert compute_total_characters([\"aa\", \"abc\"]) == 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Open the notebook http://nbviewer.ipython.org/github/zonca/challenges/blob/master/challenge-notebook-3.ipynb, the solution to this challenge is below"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cell_tags": [],
"collapsed": false
},
"outputs": [],
"source": [
"import pandas as pd\n",
"import statsmodels.api as sm\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def fahr_to_celsius(temp_fahr):\n",
" \"\"\"Convert temperature from Fahrenheit to Celsius\"\"\"\n",
" temp_celsius = (temp_fahr - 32) * 5 / 9.0\n",
" return temp_celsius\n",
"\n",
"def analyze(data):\n",
" \"\"\"Perform regression analysis on mosquito data\n",
" \n",
" Performs a linear regression based on rainfall.\n",
" Creates a plot of the result and returns fit parameters.\n",
" \n",
" Parameters\n",
" ----------\n",
" data : pandas.Dataframe\n",
" Column named 'temperature', 'rainfall' and 'mosquitos'.\n",
" \n",
" Returns\n",
" -------\n",
" parameters_rainfall : pandas.Series\n",
" Fit parameters named Intercept and rainfall\n",
" parameters_temperature : pandas.Series\n",
" Fit parameters named Intercept and temperature\n",
" \"\"\"\n",
" data['temperature'] = fahr_to_celsius(data['temperature'])\n",
" output = []\n",
" for variable in ['rainfall', 'temperature']:\n",
" # linear fit\n",
" regr_results = sm.OLS.from_formula('mosquitos ~ ' + variable, data).fit()\n",
" parameters = regr_results.params\n",
" line_fit = parameters['Intercept'] + parameters[variable] * data[variable]\n",
" # plotting\n",
" plt.figure()\n",
" plt.plot(data[variable], data['mosquitos'], '.', label=\"data\")\n",
" plt.plot(data[variable], line_fit, 'red', label=\"fit\")\n",
" plt.xlabel(variable)\n",
" plt.ylabel('mosquitos')\n",
" plt.legend(loc='best')\n",
" output.append(parameters)\n",
" return output"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"data_A2 = pd.read_csv('A2_mosquito_data.csv')\n",
"parameters_A2 = analyze(data_A2)\n",
"print(parameters_A2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"cell_tags": []
},
"source": [
"#### Key Points\n",
"\n",
"* Use `for variable in collection` to process the elements of a collection one at a time.\n",
"* The body of a for loop must be indented.\n",
"* Use `len(thing)` to determine the length of something that contains other values.\n",
"* `[value1, value2, value3, ...]` creates a list.\n",
"* Lists are indexed and sliced in the same way as strings and arrays."
]
}
],
"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.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}