Showing preview only (719K chars total). Download the full file or copy to clipboard to get everything.
Repository: leriomaggio/python-in-a-notebook
Branch: master
Commit: ac68538f9a25
Files: 34
Total size: 696.2 KB
Directory structure:
gitextract_p4ilgqem/
├── .gitignore
├── 00 Programming Environment.ipynb
├── 01 Hello World.ipynb
├── 01 Introducing the IPython Notebook.ipynb
├── 02 Variable Strings and Numbers.ipynb
├── 03 List and Tuples and Sets.ipynb
├── 04 If Statements.ipynb
├── 05 While Loops and User input.ipynb
├── 06 Dictionaries.ipynb
├── 07 Introduction to Functions.ipynb
├── 07 More Functions.ipynb
├── 08 Classes and OOP.ipynb
├── 09 Exceptions.ipynb
├── 10 External files.ipynb
├── 11 Persistence.ipynb
├── Coding Style (PEP8).ipynb
├── Importing Modules.ipynb
├── Index.ipynb
├── LICENSE
├── README.md
├── Resources and References.ipynb
├── The Zen of Python.ipynb
├── data/
│ ├── data.txt
│ ├── data2.txt
│ ├── dbase1
│ ├── elderlyHeightWeight.csv
│ ├── male_data.tsv
│ ├── new_data.csv
│ ├── test.txt
│ └── testdb
├── files/
│ ├── example.css
│ └── makedicts.py
├── multiplying.py
└── rocket.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
TOC.ipynb
__pycache__
data/BODY_COMPOSITION_DATA_4_ASSIGNMENT.csv
data/BODY_COMPOSITION_DATA_4_ASSIGNMENT.tsv
data/elderly_bmi.csv
data/elderlyPhenoData_small.csv
data/energy.txt
data/energy_intake.txt
data/helium.txt
data/marathon.csv
data/module_grades.tsv
data/nhanes.csv
data/nhanes_bmi.csv
data/obesity_stats.xlsx
data/pparg_prot.fa
data/run10.txt
data/states.csv
Untitled.ipynb
================================================
FILE: 00 Programming Environment.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Programming Environment\n",
"\n",
"Your \"programming environment\" is the computer you do your work on, and all the software that is installed on your computer that helps you write and run programs. Some systems are better for programming than others, but the best system to learn on is probably the one you are using right now. This section will help you get a system set up that will let you start writing programs quickly."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a name='overview'></a>Overview\n",
"===\n",
"Our goal is to help you get Python up and running on your computer, so that you can write and run your own programs. To do this, we want to:\n",
"\n",
"- Find out if Python is already installed on your computer.\n",
"- Install Python, if it is not already installed.\n",
"\n",
"----\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Disclaimer\n",
"\n",
"If you already have a working Python installation, please feel free to skip this notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Anaconda Python Distribution\n",
"\n",
"We use **Python 3.5** included in the [**Anaconda**](https://store.continuum.io/cshop/anaconda/) distribution by \n",
"[**Continuum Analytics**](http://www.continuum.io/).\n",
"\n",
"Anaconda is a completely free enterprise-ready Python distribution for large-scale data processing, predictive analytics, and scientific computing. \n",
"\n",
"Apart from that, Anaconda ships with easy-to-use installers for almost every platform, that wuold drastically reduce the \n",
"burden of setting up the environment (exp. on [Windows](http://continuum.io/downloads#34))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Quick Start Guide\n",
"\n",
"If you've installed **Anaconda** but you don't know what do then, please take a look at the [Quick Start Guide](https://store.continuum.io/static/img/Anaconda-Quickstart.pdf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Standard or System Python Distributions\n",
"\n",
"If you would like to install more \"classical\" Python distributions (e.g., those available on the \n",
"[`python.org`](https://www.python.org/downloads/) web site), please take a look at this notebook:\n",
"\n",
"\n",
"[Programming Environment](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/programming_environment.ipynb)"
]
}
],
"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.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
================================================
FILE: 01 Hello World.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# \"Hello world\" in Python!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"When programmers are learning a new language, we tend to write a one-line program that prints some version of the message \"Hello world!\" this is a simple program that shows whether your computer is properly set up to run Python programs."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Python world!\n"
]
}
],
"source": [
"print('Hello Python world!')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"If it works, congratulations! You just ran your first Python program."
]
}
],
"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.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
================================================
FILE: 01 Introducing the IPython Notebook.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Introducing the IPython Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"### Aron Ahmadia (US Army ERDC) and David Ketcheson (KAUST)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"### Teaching Numerical Methods with IPython Notebooks, SciPy 2014"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/80x15.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" property=\"dct:title\">This lecture</span> by <a xmlns:cc=\"http://creativecommons.org/ns#\" property=\"cc:attributionName\" rel=\"cc:attributionURL\">Aron Ahmadia and David Ketcheson</a> is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>. All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n",
"\n",
"**NOTE**: Some changes have been applied to make this notebook compliant with **Python 3**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## What is this?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"This is a gentle introduction to the IPython Notebook aimed at lecturers who wish to incorporate it in their teaching, written in an IPython Notebook. This presentation adapts material from the [IPython official documentation](http://nbviewer.ipython.org/github/ipython/ipython/blob/2.x/examples/Notebook)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## What is an IPython Notebook?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"An IPython Notebook is a:\n",
"\n",
"**[A]** Interactive environment for writing and running code \n",
"**[B]** Weave of code, data, prose, equations, analysis, and visualization \n",
"**[C]** Tool for prototyping new code and analysis \n",
"**[D]** Reproducible workflow for scientific research \n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"**[E]** **All of the above**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Writing and Running Code"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The IPython Notebook consists of an ordered list of cells. \n",
"\n",
"There are four important cell types:\n",
"\n",
"* **Code**\n",
"* **Markdown**\n",
"* **Heading**\n",
"* **Raw**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"We briefly introduce how Code Cells work here. We will return to the other three cell types later."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Code Cells"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"# This is a code cell made up of Python comments\n",
"# We can execute it by clicking on it with the mouse\n",
"# then clicking the \"Run Cell\" button"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, World\n"
]
}
],
"source": [
"# A comment is a pretty boring piece of code\n",
"# This code cell generates \"Hello, World\" when executed\n",
"\n",
"print(\"Hello, World\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAEACAYAAABI5zaHAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAADu1JREFUeJzt3H+s3fVdx/Hni1ZwSlpdzYprR6sIU5ZgxQSKxHCWaUYx\nUv9Y3OYSFP8hyyZEErNJlrR/6h/GDOeCjYysy+bYyLKhA8WF3ZD5RzeBhjrajWULlDKuIaxBfsSU\n+faP86XcXW57zr0993xPP/f5SL7p98f7fr/vnJ7zOp/zOfd7U1VIktpyTt8NSJImz3CXpAYZ7pLU\nIMNdkhpkuEtSgwx3SWrQyHBPcl6SA0keTXIoyZ5T1N2e5IkkB5PsmHyrkqRxrR9VUFX/m+SdVfVy\nknXAfyS5v6q++VpNkl3ARVV1cZIrgTuAnavXtiTpdMaalqmql7vV8xi+ISy+82k3sL+rPQBsTLJ5\nUk1KkpZnrHBPck6SR4FngX+vqm8tKtkCHF2wfazbJ0nqwbgj9/+rqt8AtgJXJrl0dduSJJ2JkXPu\nC1XVC0m+DlwLPL7g0DHgbQu2t3b7fkIS/5CNJK1AVWU59eP8tswvJNnYrb8J+F3gyKKye4Ebupqd\nwPGqmj9Fgy5V7Nmzp/ceXv+jcdXzMgs91Ew8P2fleTELi4/F68tKjDNy/0Xg00nOYfhmcHdV3Zfk\npuFrofZ129cl+R7wEnDjirqRJE3EOL8KeQi4fIn9/7Bo+8MT7EuSdAa8Q7Ung8Gg7xY0g3xevM7H\n4sxkpfM5K7pYUtO8nkZLwhtvW5h6FzPQA0BWPL8praYk1KS/UJUknX0Md0lqkOEuSQ0y3CWpQYa7\nJDXIcJekBhnuktQgw12SGmS4S1KDDHdJapDhLkkNMtwlqUGGuyQ1yHCXpAYZ7pLUIMNdkhpkuEtS\ngwx3SWqQ4S5JDTLcJalBhrskNchwl6QGGe6S1CDDXZIaZLhLUoMMd0lq0MhwT7I1yYNJvp3kUJKb\nl6i5JsnxJI90y8dWp11J0jjWj1HzKnBrVR1Mcj7wcJIHqurIorqHqur6ybcoSVqukSP3qnq2qg52\n6y8Ch4EtS5Rmwr1JklZoWXPuSbYDO4ADSxy+KsnBJF9NcukEepMkrdA40zIAdFMy9wC3dCP4hR4G\nLqyql5PsAr4MXDK5NiVJyzFWuCdZzzDYP1NVX1l8fGHYV9X9ST6Z5M1V9fzi2r17955cHwwGDAaD\nFbQtSe2am5tjbm7ujM6RqhpdlOwHnquqW09xfHNVzXfrVwBfqKrtS9TVONfT9CQB+v4/mYUeAILP\nT82iJFTVsr7XHDlyT3I18AHgUJJHGb4KbwO2AVVV+4D3JPkgcAJ4BXjvcpuXJE3OWCP3iV3MkfvM\nceS+kCN3zaaVjNy9Q1WSGmS4S1KDDHdJapDhLkkNMtwlqUGGuyQ1yHCXpAYZ7pLUIMNdkhpkuEtS\ngwx3SWqQ4S5JDTLcJalBhrskNchwl6QGGe6S1CDDXZIaZLhLUoMMd0lqkOEuSQ0y3CWpQYa7JDXI\ncJekBhnuktQgw12SGmS4S1KDDHdJapDhLkkNMtwlqUEjwz3J1iQPJvl2kkNJbj5F3e1JnkhyMMmO\nybcqSRrX+jFqXgVuraqDSc4HHk7yQFUdea0gyS7goqq6OMmVwB3AztVpWZI0ysiRe1U9W1UHu/UX\ngcPAlkVlu4H9Xc0BYGOSzRPuVZI0pmXNuSfZDuwADiw6tAU4umD7GG98A5AkTck40zIAdFMy9wC3\ndCP4Fdm7d+/J9cFgwGAwWOmpzmoXXLCd+fkn+25D0gyam5tjbm7ujM6RqhpdlKwH/gW4v6o+vsTx\nO4CvV9Xd3fYR4Jqqml9UV+Ncby1IAszCYzELfcxCDwDB56dmURKqKsv5mXGnZT4FPL5UsHfuBW7o\nmtgJHF8c7JKk6Rk5ck9yNfAQcIjh8KqA24BtQFXVvq7uE8C1wEvAjVX1yBLncuTeceQ+az2AI3fN\nqpWM3MealpkUw/11hvus9QCGu2bVak7LSJLOIoa7JDXIcJekBhnuktQgw12SGmS4S1KDDHdJapDh\nLkkNMtwlqUGGuyQ1yHCXpAYZ7pLUIMNdkhpkuEtSgwx3SWqQ4S5JDTLcJalBhrskNchwl6QGGe6S\n1CDDXZIaZLhLUoMMd0lqkOEuSQ0y3CWpQYa7JDXIcJekBhnuktSgkeGe5M4k80keO8Xxa5IcT/JI\nt3xs8m1KkpZj/Rg1dwF/B+w/Tc1DVXX9ZFqSJJ2pkSP3qvoG8KMRZZlMO5KkSZjUnPtVSQ4m+WqS\nSyd0TknSCo0zLTPKw8CFVfVykl3Al4FLTlW8d+/ek+uDwYDBYDCBFiSpHXNzc8zNzZ3ROVJVo4uS\nbcA/V9VlY9T+APjNqnp+iWM1zvXWgiTALDwWs9DHLPQAEHx+ahYloaqWNf097rRMOMW8epLNC9av\nYPiG8YZglyRNz8hpmSSfAwbApiRPAXuAc4Gqqn3Ae5J8EDgBvAK8d/XalSSNY6xpmYldzGmZk5yW\nmbUewGkZzarVnJaRJJ1FDHdJapDhLkkNMtwlqUGGuyQ1yHCXpAYZ7pLUIMNdkhpkuEtSgwx3SWqQ\n4S5JDTLcJalBhrskNchwl6QGGe6S1CDDXZIaZLhLUoMMd0lqkOEuSQ0y3CWpQYa7JDXIcJekBhnu\nktQgw12SGmS4S1KDDHdJapDhLkkNMtwlqUEjwz3JnUnmkzx2mprbkzyR5GCSHZNtUZK0XOOM3O8C\n3n2qg0l2ARdV1cXATcAdE+pNkrRCI8O9qr4B/Og0JbuB/V3tAWBjks2TaU+StBLrJ3COLcDRBdvH\nun3zSxU/88wzE7jkyp133nls2rSp1x4kabVNItyXZdu2t59cX7fuXNatO2+q1z9x4jgbN27iueee\nnup1JZ2dLrhgO/PzT/bdxrJNItyPAW9bsL2127ekV1/9nwXrE7j6Mm3YcBnPPXcIqOlf/Cek5+tL\nGscw2M++vBj3VyFzmrPfC9wAkGQncLyqlpySkSRNx8iRe5LPAQNgU5KngD3AuUBV1b6qui/JdUm+\nB7wE3LiaDUuSRkvV9D5uJKm+P95s2HAZL7wwK9MyffcAs9HHLPQAEKb5etDZIZmF52eoqmXNzXiH\nqiQ1yHCXpAYZ7pLUIMNdkhpkuEtSgwx3SWqQ4S5JDTLcJalBhrskNchwl6QGGe6S1CDDXZIaZLhL\nUoMMd0lqkOEuSQ0y3CWpQYa7JDXIcJekBhnuktQgw12SGmS4S1KDDHdJapDhLkkNMtwlqUGGuyQ1\nyHCXpAYZ7pLUIMNdkho0VrgnuTbJkSTfTfKRJY5fk+R4kke65WOTb1WSNK71owqSnAN8AngX8Azw\nrSRfqaoji0ofqqrrV6FHSdIyjTNyvwJ4oqqerKoTwOeB3UvUZaKdSZJWbJxw3wIcXbD9dLdvsauS\nHEzy1SSXTqQ7SdKKjJyWGdPDwIVV9XKSXcCXgUsmdG5J0jKNE+7HgAsXbG/t9p1UVS8uWL8/ySeT\nvLmqnn/j6fYuWB90iyTpdXPdsnKpqtMXJOuA7zD8QvWHwDeB91fV4QU1m6tqvlu/AvhCVW1f4lwF\np7/eatuw4TJeeOEQffcx/Iqi7x5gNvqYhR4AwqjXg9aeZBaen6GqlvW95siRe1X9OMmHgQcYztHf\nWVWHk9w0PFz7gPck+SBwAngFeO/ym5ckTcrIkftEL+bIfYFZGA3AbPQxCz2AI3ct5WwduXuHqiQ1\nyHCXpAYZ7pLUIMNdkhpkuEtSgwx3SWqQ4S5JDTLcJalBhrskNchwl6QGGe6S1CDDXZIaZLhLUoMM\nd0lqkOEuSQ0y3CWpQYa7JDXIcJekBhnuktQgw12SGmS4S1KDDHdJapDhLkkNMtwlqUGGuyQ1yHCX\npAYZ7pLUIMNdkho0VrgnuTbJkSTfTfKRU9TcnuSJJAeT7Jhsm5Kk5RgZ7knOAT4BvBt4B/D+JL+6\nqGYXcFFVXQzcBNyxCr1KzZubm+u7hZnhY3Fmxhm5XwE8UVVPVtUJ4PPA7kU1u4H9AFV1ANiYZPNE\nO5XWAAPtdT4WZ2accN8CHF2w/XS373Q1x5aokSRNyfppX3DDht+f9iV/wiuv/KDX60vSNKSqTl+Q\n7AT2VtW13fZHgaqqv15Qcwfw9aq6u9s+AlxTVfOLznX6i0mSllRVWU79OCP3bwG/kmQb8EPgfcD7\nF9XcC3wIuLt7Mzi+ONhX0pwkaWVGhntV/TjJh4EHGM7R31lVh5PcNDxc+6rqviTXJfke8BJw4+q2\nLUk6nZHTMpKks8/U7lAd50aotSDJ1iQPJvl2kkNJbu67pz4lOSfJI0nu7buXviXZmOSLSQ53z48r\n++6pD0n+PMl/JXksyWeTnNt3T9OU5M4k80keW7Dv55M8kOQ7Sf4tycZR55lKuI9zI9Qa8ipwa1W9\nA7gK+NAafiwAbgEe77uJGfFx4L6q+jXg14HDPfczdUneCvwZcHlVXcZw6vh9/XY1dXcxzMqFPgp8\nrareDjwI/OWok0xr5D7OjVBrQlU9W1UHu/UXGb6A1+Q9AUm2AtcB/9h3L31LsgH47aq6C6CqXq2q\nF3puqy/rgJ9Nsh74GeCZnvuZqqr6BvCjRbt3A5/u1j8N/MGo80wr3Me5EWrNSbId2AEc6LeT3vwt\n8BeAX/zALwHPJbmrm6bal+RNfTc1bVX1DPA3wFMMb4Y8XlVf67ermfCW134DsaqeBd4y6gf8q5A9\nSXI+cA9wSzeCX1OS/B4w332KSbesZeuBy4G/r6rLgZcZfhRfU5L8HMNR6jbgrcD5Sf6o365m0sgB\n0bTC/Rhw4YLtrd2+Nan7uHkP8Jmq+krf/fTkauD6JN8H/gl4Z5L9PffUp6eBo1X1n932PQzDfq35\nHeD7VfV8Vf0Y+BLwWz33NAvmX/t7XUkuAP571A9MK9xP3gjVffP9PoY3Pq1VnwIer6qP991IX6rq\ntqq6sKp+meHz4cGquqHvvvrSfeQ+muSSbte7WJtfND8F7Ezy00nC8HFYc18s88ZPs/cCf9Kt/zEw\nclA4lb8tc6oboaZx7VmT5GrgA8ChJI8y/Hh1W1X9a7+daQbcDHw2yU8B32cN3gxYVd9Mcg/wKHCi\n+3dfv11NV5LPAQNgU5KngD3AXwFfTPKnwJPAH448jzcxSVJ7/EJVkhpkuEtSgwx3SWqQ4S5JDTLc\nJalBhrskNchwl6QGGe6S1KD/B19YUsQgbm54AAAAAElFTkSuQmCC\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x1047ccf60>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Code cells can also generate graphical output\n",
"%matplotlib inline\n",
"import matplotlib\n",
"matplotlib.pyplot.hist([0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 10]);"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Modal editor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Starting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Edit mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Edit mode is indicated by a green cell border and a prompt showing in the editor area:\n",
"\n",
"<img src=\"./files/images/edit_mode.png\">\n",
"\n",
"When a cell is in edit mode, you can type into the cell, like a normal text editor."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"<div class=\"alert alert-success\" style=\"margin: 10px\">\n",
"Enter edit mode by pressing `enter` or using the mouse to click on a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"<div class=\"alert alert-success\" style=\"margin: 10px\">\n",
"While in edit mode, tab-completion works for variables the kernel knows about from executing previous cells.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Command mode"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Command mode is indicated by a grey cell border:\n",
"\n",
"<img src=\"./files/images/command_mode.png\">\n",
"\n",
"When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"<div class=\"alert alert-error\" style=\"margin: 10px\">\n",
"Don't try to type into a cell in command mode; unexpected things will happen!\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"<div class=\"alert alert-success\" style=\"margin: 10px\">\n",
"Enter command mode by pressing `esc` or using the mouse to click *outside* a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Mouse navigation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:\n",
"\n",
"<img src=\"./files/images/menubar_toolbar.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"The first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.\n",
"\n",
"If you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"The second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. Similarly, to copy a cell you would select it and click the \"Copy\" button in the toolbar or the \"Edit:Copy\" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.\n",
"\n",
"Markdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the \"Play\" button in the toolbar or the \"Cell:Run\" menu item. To unrender the selected cell, double click on the cell."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Keyboard Navigation"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The most important keyboard shortcuts are `enter`, which enters edit mode, and `esc`, which enters command mode.\n",
"\n",
"In edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In command mode, the entire keyboard is available for shortcuts:"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Here the rough order in which the IPython Developers recommend learning the command mode **shortcuts**:\n",
"\n",
"1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n",
"2. Saving the notebook: `s`\n",
"2. Cell types: `y`, `m`, `1-6`, `t`\n",
"3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n",
"4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n",
"5. Kernel operations: `i`, `0`"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"I personally (& humbly) suggest learning `h` first!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## The IPython Notebook Architecture"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"So far, we have learned the basics of using IPython Notebooks.\n",
"\n",
"For simple demonstrations, the typical user doesn't need to understand how the computations are being handled, but to successfully write and present computational notebooks, **you** will need to understand how the notebook architecture works."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"A *live* notebook is composed of an interactive web page (the front end), a running IPython session (the kernel or back end), and a web server responsible for handling communication between the two (the, err..., middle-end)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"A *static* notebook, as for example seen on NBViewer, is a static view of the notebook's content. The default format is HTML, but a notebook can also be output in PDF or other formats."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The centerpiece of an IPython Notebook is the \"kernel\", the IPython instance responsible for executing all code. Your IPython kernel maintains its state between executed cells."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n"
]
}
],
"source": [
"x = 0\n",
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"x += 1\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"There are two important actions for interacting with the kernel. The first is to interrupt it. This is the same as sending a Control-C from the command line. The second is to restart it. This completely terminates the kernel and starts it anew. None of the kernel state is saved across a restart. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Markdown cells"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Text can be added to IPython Notebooks using Markdown cells. Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:\n",
"\n",
"<http://daringfireball.net/projects/markdown/>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Markdown basics"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Text formatting"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"You can make text *italic* or **bold** or `monospace`"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Itemized Lists"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* One\n",
" - Sublist\n",
" - This\n",
" - Sublist\n",
" - That\n",
" - The other thing\n",
"* Two\n",
" - Sublist\n",
"* Three\n",
" - Sublist"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Enumerated Lists"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Here we go\n",
" 1. Sublist\n",
" 2. Sublist\n",
"2. There we go\n",
"3. Now this"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Horizontal Rules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n",
"---\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Blockquotes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge. -- Rear Admiral Grace Hopper"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Links"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[IPython's website](http://ipython.org)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Code"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a code snippet: \n",
" \n",
"```Python\n",
"def f(x):\n",
" \"\"\"a docstring\"\"\"\n",
" return x**2\n",
"```\n",
" \n",
"This is an example of a **Python** function"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"You can also use triple-backticks to denote code blocks.\n",
"This also allows you to choose the appropriate syntax highlighter.\n",
"\n",
"```C\n",
"if (i=0; i<n; i++) {\n",
" printf(\"hello %d\\n\", i);\n",
" x += 4;\n",
"}\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Tables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Time (s) | Audience Interest\n",
"---------|------------------\n",
" 0 | High\n",
" 1 | Medium\n",
" 5 | Facebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Images"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### YouTube"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"data": {
"text/html": [
"\n",
" <iframe\n",
" width=\"400\"\n",
" height=\"300\"\n",
" src=\"https://www.youtube.com/embed/vW_DRAJ0dtc\"\n",
" frameborder=\"0\"\n",
" allowfullscreen\n",
" ></iframe>\n",
" "
],
"text/plain": [
"<IPython.lib.display.YouTubeVideo at 0x1048032e8>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import YouTubeVideo\n",
"YouTubeVideo('vW_DRAJ0dtc')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Other HTML"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<strong> Be Bold! </strong>"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Mathematical Equations"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Courtesy of MathJax, you can beautifully render mathematical expressions, both inline: \n",
"$e^{i\\pi} + 1 = 0$, and displayed:\n",
"\n",
"$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Equation Environments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also use a number of equation environments, such as `align`:\n",
"\n",
"\\begin{align}\n",
" x &= 4 \\\\\n",
"y+z &= x\n",
"\\end{align}\n",
"\n",
"[A full list of available TeX and LaTeX commands is maintained by Dr. Carol Burns.](http://www.onemathematicalcat.org/MathJaxDocumentation/TeXSyntax.htm)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Other Useful MathJax Notes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* inline math is demarcated by `$ $`, or `\\( \\)`\n",
"* displayed math is demarcated by `$$ $$` or `\\[ \\]`\n",
"* displayed math environments can also be directly demarcated by `\\begin` and `\\end`\n",
"* `\\newcommand` and `\\def` are supported, *within* areas MathJax processes (such as in a `\\[ \\]` block)\n",
"* equation numbering is not officially supported, but it can be indirectly enabled"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## A Note about Notebook Security"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By default, a notebook downloaded to a new computer is *untrusted*\n",
"\n",
"* HTML and Javascript in Markdown cells is now *never* executed\n",
"* HTML and Javascript code outputs must be explicitly *re-executed*\n",
"* Some of these restrictions can be mitigrated through shared accounts (Sage MathCloud) and secrets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"More information on notebook security is in the [IPython Notebook documentation](http://ipython.org/ipython-doc/stable/notebook/security.html)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Magics"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"IPython kernels execute a superset of the Python language. The extension functions, commonly referred to as *magics*, come in two variants. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Line Magics"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"* A *line magic* looks like a command line call. The most important of these is `%matplotlib inline`, which embeds all matplotlib plot output as images in the notebook itself."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Variable Type Data/Info\n",
"----------------------------------\n",
"YouTubeVideo type <class 'IPython.lib.display.YouTubeVideo'>\n",
"matplotlib module <module 'matplotlib' from<...>/matplotlib/__init__.py'>\n",
"x int 1\n"
]
}
],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Cell Magics"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"* A *cell magic* takes its entire cell as an argument. Although there are a number of useful cell magics, you may find `%%timeit` to be useful for exploring code performance."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The slowest run took 7.40 times longer than the fastest. This could mean that an intermediate result is being cached \n",
"10000 loops, best of 3: 30.7 µs per loop\n"
]
}
],
"source": [
"%%timeit\n",
"\n",
"import numpy as np\n",
"np.sum(np.random.rand(1000))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Execute Code as Python 2"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'long'>\n"
]
}
],
"source": [
"%%python2\n",
"\n",
"i = 10**60\n",
"print type(i)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### Interacting with the Command Line"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"IPython supports one final trick, the ability to interact directly with your shell by using the `!` operator."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"00 Programming Environment.ipynb\r\n",
"01 Hello World.ipynb\r\n",
"01 Introducing the IPython Notebook.ipynb\r\n",
"02 Variable Strings and Numbers.ipynb\r\n",
"03 List and Tuples.ipynb\r\n",
"04 If Statements.ipynb\r\n",
"05 While Loops and User input.ipynb\r\n",
"06 Dictionaries.ipynb\r\n",
"Index.ipynb\r\n",
"LICENSE\r\n",
"README.md\r\n",
"Resources and References.ipynb\r\n",
"TOC.ipynb\r\n",
"\u001b[34mfiles\u001b[m\u001b[m\r\n"
]
}
],
"source": [
"!ls"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"x = !ls"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['00 Programming Environment.ipynb', '01 Hello World.ipynb', '01 Introducing the IPython Notebook.ipynb', '02 Variable Strings and Numbers.ipynb', '03 List and Tuples.ipynb', '04 If Statements.ipynb', '05 While Loops and User input.ipynb', '06 Dictionaries.ipynb', 'Index.ipynb', 'LICENSE', 'README.md', 'Resources and References.ipynb', 'TOC.ipynb', 'files']\n"
]
}
],
"source": [
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## A Note about Notebook Version Control"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"The IPython Notebook is stored using canonicalized JSON for ease of use with version control systems.\n",
"\n",
"There are two things to be aware of:\n",
"\n",
"* By default, IPython embeds all content and saves kernel execution numbers. You may want to get in the habit of clearing all cells before committing.\n",
"\n",
"* As of IPython 2.0, all notebooks are signed on save. This increases the chances of a commit collision during merge, forcing a manual resolution. Either signature can be safely deleted in this situation."
]
}
],
"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.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
================================================
FILE: 02 Variable Strings and Numbers.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Variables, Strings, and Numbers"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"In this section, you will learn to store information in variables. \n",
"\n",
"You will learn about two types of data: strings, which are sets of characters, and numerical data types."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"## <a name=\"top\"></a>Contents\n",
"---\n",
"- [Variables](#variables)\n",
" - [Example](#example)\n",
" - [Naming rules](#naming_rules)\n",
" - [NameError](#name_error)\n",
" - [Exercises](#exercises_variables)\n",
"- [Strings](#strings)\n",
" - [Single and double quotes](#single_double_quotes)\n",
" - [Changing case](#changing_case)\n",
" - [Combining strings (concatenation)](#concatenation)\n",
" - [Whitespace](#whitespace)\n",
" - [Exercises](#exercises_strings)\n",
"- [Numbers](#numbers)\n",
" - [Integer operations](#integer_operations)\n",
" - [Floating-point numbers](#floats)\n",
" - [Exercises](#exercises_numbers)\n",
" - [Challenges](#challenges_numbers)\n",
"- [Comments](#comments)\n",
" - [What makes a good comment?](#good_comments)\n",
" - [When should you write comments?](#when_comments)\n",
" - [Exercises](#exercises_comments)\n",
"- [Overall Challenges](#challenges_overall)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='variables'></a>Variables\n",
"===\n",
"A variable holds a value."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='example'></a>Example\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Python world!\n"
]
}
],
"source": [
"message = \"Hello Python world!\"\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"A variable holds a value. You can change the value of a variable at any point."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Python world!\n",
"Python is my favorite language!\n"
]
}
],
"source": [
"message = \"Hello Python world!\"\n",
"print(message)\n",
"\n",
"message = \"Python is my favorite language!\"\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='naming_rules'></a>Naming rules\n",
"---\n",
"- Variables can only contain letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number.\n",
"- Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of \"student name\".\n",
"- You cannot use [Python keywords](http://docs.python.org/3/reference/lexical_analysis.html#keywords) as variable names.\n",
"- Variable names should be descriptive, without being too long. For example mc_wheels is better than just \"wheels\", and number_of_wheels_on_a_motorycle.\n",
"- Be careful about using the lowercase letter l and the uppercase letter O in places where they could be confused with the numbers 1 and 0."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='name_error'></a>NameError\n",
"---\n",
"There is one common error when using variables, that you will almost certainly encounter at some point. Take a look at this code, and see if you can figure out why it causes an error."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'mesage' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-3-7966723379c3>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmessage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"Thank you for sharing Python with the world, Guido!\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmesage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'mesage' is not defined"
]
}
],
"source": [
"message = \"Thank you for sharing Python with the world, Guido!\"\n",
"print(mesage)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Let's look through this error message. First, we see it is a NameError. Then we see the file that caused the error, and a green arrow shows us what line in that file caused the error. Then we get some more specific feedback, that \"name 'mesage' is not defined\"."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You may have already spotted the source of the error. We spelled message two different ways. Python does not care whether we use the variable name \"message\" or \"mesage\". Python only cares that the spellings of our variable names match every time we use them.\n",
"\n",
"This is pretty important, because it allows us to have a variable \"name\" with a single name in it, and then another variable \"names\" with a bunch of names in it."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"We can fix **NameErrors** by making sure all of our variable names are spelled consistently."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Thank you for sharing Python with the world, Guido!\n"
]
}
],
"source": [
"message = \"Thank you for sharing Python with the world, Guido!\"\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"In case you didn't know [Guido](http://en.wikipedia.org/wiki/Guido_van_Rossum) [van Rossum](http://www.python.org/~guido/) created the Python language over 20 years ago, and he is considered Python's [Benevolent Dictator for Life](http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life). Guido still signs off on all major changes to the core Python language."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_variables'></a>Exercises\n",
"---\n",
"#### Hello World - variable\n",
"\n",
"- Store your own version of the message \"Hello World\" in a variable, and print it.\n",
"\n",
"#### One Variable, Two Messages:\n",
"- Store a message in a variable, and then print that message.\n",
"- Store a new message in the same variable, and then print that new message."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.1 : Hello World - Variable\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.2 : One Variable, Two Messages\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='strings'></a>Introduction to Strings\n",
"===\n",
"Strings are sets of characters. Strings are easier to understand by looking at some examples."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='single_double_quotes'></a>Single and double quotes\n",
"---\n",
"Strings are contained by either single or double quotes."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"my_string = \"This is a double-quoted string.\"\n",
"my_string = 'This is a single-quoted string.'"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This lets us make strings that contain quotations."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"quote = \"Linus Torvalds once said, \\\n",
" 'Any program is only as good as it is useful.'\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Multiline Strings\n",
"\n",
"In case we need to create a multiline string, there is the **triple-quote** to the rescue:\n",
"`'''`"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is a string where I \n",
"can confortably write on multiple lines\n",
"without worrynng about to use the escape character \"\\\" as in\n",
"the previsou example. \n",
"As you'll see, the original string formatting is preserved.\n",
"\n"
]
}
],
"source": [
"multiline_string = '''This is a string where I \n",
"can confortably write on multiple lines\n",
"without worring about to use the escape character \"\\\\\" as in\n",
"the previsou example. \n",
"As you'll see, the original string formatting is preserved.\n",
"'''\n",
"\n",
"print(multiline_string)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='changing_case'></a>Changing case\n",
"---\n",
"You can easily change the case of a string, to present it the way you want it to look."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eric\n",
"Eric\n"
]
}
],
"source": [
"first_name = 'eric'\n",
"\n",
"print(first_name)\n",
"print(first_name.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"It is often good to store data in lower case, and then change the case as you want to for presentation. This catches some TYpos. It also makes sure that 'eric', 'Eric', and 'ERIC' are not considered three different people.\n",
"\n",
"Some of the most common cases are lower, title, and upper."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eric\n",
"Eric\n",
"ERIC\n",
"eric\n"
]
}
],
"source": [
"first_name = 'eric'\n",
"\n",
"print(first_name)\n",
"print(first_name.title())\n",
"print(first_name.upper())\n",
"\n",
"first_name_titled = 'Eric'\n",
"print(first_name_titled.lower())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note**: Please notice that the original strings remain **always** unchanged"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eric\n",
"Eric\n"
]
}
],
"source": [
"print(first_name)\n",
"print(first_name_titled)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You will see this syntax quite often, where a variable name is followed by a dot and then the name of an action, followed by a set of parentheses. The parentheses may be empty, or they may contain some values.\n",
"\n",
" variable_name.action()\n",
"\n",
"In this example, the word \"action\" is the name of a **method**. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"A method is something that can be done to a variable."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The methods `lower`, `title`, and `upper` are all functions that have been written into the Python language, which do something to **strings**. \n",
"\n",
"Later on, you will learn to write your own methods."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='concatenation'></a>Combining strings (concatenation)\n",
"---\n",
"It is often very useful to be able to combine strings into a message or page element that we want to display. Again, this is easier to understand through an example."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ada Lovelace\n"
]
}
],
"source": [
"first_name = 'ada'\n",
"last_name = 'lovelace'\n",
"\n",
"full_name = first_name + ' ' + last_name\n",
"\n",
"print(full_name.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The plus sign combines two strings into one, which is called **concatenation**. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You can use as many plus signs as you want in composing messages. In fact, many web pages are written as giant strings which are put together through a long series of string concatenations."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ada Lovelace was considered the world's first computer programmer.\n"
]
}
],
"source": [
"first_name = 'ada'\n",
"last_name = 'lovelace'\n",
"full_name = first_name + ' ' + last_name\n",
"\n",
"message = full_name.title() + ' ' + \\\n",
" \"was considered the world's first computer programmer.\"\n",
"\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"If you don't know who Ada Lovelace is, you might want to go read what [Wikipedia](http://en.wikipedia.org/wiki/Ada_Lovelace) or the [Computer History Museum](http://www.computerhistory.org/babbage/adalovelace/) have to say about her. Her life and her work are also the inspiration for the [Ada Initiative](http://adainitiative.org/faq/about-ada-lovelace/), which supports women who are involved in technical fields."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Brief introduction to string formatting"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"String Template: The result of the calculation of {calc} is {res}\n",
"The result of the calculation of (3*4)+2 is 14\n"
]
}
],
"source": [
"string_template = 'The result of the calculation of {calc} is {res}'\n",
"print(\"String Template: \", string_template)\n",
"\n",
"print(string_template.format(calc='(3*4)+2', res=(3*4)+2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### There's much more than that!\n",
"\n",
"For further information about *String formatting*, see the official online documentation about the [`string`](https://docs.python.org/3/library/string.html) module."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='whitespace'></a>Whitespace\n",
"---\n",
"The term \"whitespace\" refers to characters that the computer is aware of, but are invisible to readers. The most common whitespace characters are spaces, tabs, and newlines.\n",
"\n",
"Spaces are easy to create, because you have been using them as long as you have been using computers. Tabs and newlines are represented by special character combinations.\n",
"\n",
"The two-character combination \"\\t\" makes a tab appear in a string. Tabs can be used anywhere you like in a string."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello everyone!\n"
]
}
],
"source": [
"print(\"Hello everyone!\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\tHello everyone!\n"
]
}
],
"source": [
"print(\"\\tHello everyone!\")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello \teveryone!\n"
]
}
],
"source": [
"print(\"Hello \\teveryone!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"The combination \"\\n\" makes a newline appear in a string. You can use newlines anywhere you like in a string."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello everyone!\n"
]
}
],
"source": [
"print(\"Hello everyone!\")"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Hello everyone!\n"
]
}
],
"source": [
"print(\"\\nHello everyone!\")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello \n",
"everyone!\n"
]
}
],
"source": [
"print(\"Hello \\neveryone!\")"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\n",
"Hello everyone!\n"
]
}
],
"source": [
"print(\"\\n\\n\\nHello everyone!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Stripping whitespace\n",
"\n",
"Many times you will allow users to enter text into a box, and then you will read that text and use it. It is really easy for people to include extra whitespace at the beginning or end of their text. Whitespace includes spaces, tabs, and newlines.\n",
"\n",
"It is often a good idea to strip this whitespace from strings before you start working with them. For example, you might want to let people log in, and you probably want to treat 'eric ' as 'eric' when you are trying to see if I exist on your system."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You can strip whitespace from the left side, the right side, or both sides of a string."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eric \n",
" eric\n",
"eric\n"
]
}
],
"source": [
"name = ' eric '\n",
"\n",
"print(name.lstrip())\n",
"print(name.rstrip())\n",
"print(name.strip())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"It's hard to see exactly what is happening, so maybe the following will make it a little more clear:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-eric -\n",
"- eric-\n",
"-eric-\n"
]
}
],
"source": [
"name = ' eric '\n",
"\n",
"print('-' + name.lstrip() + '-')\n",
"print('-' + name.rstrip() + '-')\n",
"print('-' + name.strip() + '-')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_strings'></a>Exercises\n",
"---\n",
"#### Someone Said\n",
"- Find a quote that you like. Store the quote in a variable, with an appropriate introduction such as \"Ken Thompson once said, 'One of my most productive days was throwing away 1000 lines of code'\". Print the quote.\n",
"\n",
"#### First Name Cases\n",
"- Store your first name, in lowercase, in a variable.\n",
"- Using that one variable, print your name in lowercase, Titlecase, and UPPERCASE.\n",
"\n",
"#### Full Name\n",
"- Store your first name and last name in separate variables, and then combine them to print out your full name.\n",
"\n",
"#### About This Person\n",
"- Choose a person you look up to. Store their first and last names in separate variables.\n",
"- Use concatenation to make a sentence about this person, and store that sentence in a variable.-\n",
"- Print the sentence.\n",
"\n",
"#### Name Strip\n",
"- Store your first name in a variable, but include at least two kinds of whitespace on each side of your name.\n",
"- Print your name as it is stored.\n",
"- Print your name with whitespace stripped from the left side, then from the right side, then from both sides."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.3 : Someone Said\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.4 : First Name Cases\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.5 : Full Name\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.6 : About This Person\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.7 : Name Strip\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='numbers'></a>Numbers\n",
"===\n",
"Dealing with simple numerical data is fairly straightforward in Python, but there are a few things you should know about."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='integers'></a>Integers\n",
"---\n",
"You can do all of the basic operations with integers, and everything should behave as you expect. Addition and subtraction use the standard plus and minus symbols. Multiplication uses the asterisk, and division uses a forward slash. Exponents use two asterisks."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"print(3+2)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"print(3-2)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n"
]
}
],
"source": [
"print(3*2)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.5\n"
]
}
],
"source": [
"print(3/2)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"9\n"
]
}
],
"source": [
"print(3**2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You can use parenthesis to modify the standard order of operations."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"14\n"
]
}
],
"source": [
"standard_order = 2+3*4\n",
"print(standard_order)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20\n"
]
}
],
"source": [
"my_order = (2+3)*4\n",
"print(my_order)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='floats'></a>Floating-Point numbers\n",
"---\n",
"Floating-point numbers refer to any number with a decimal point. Most of the time, you can think of floating point numbers as decimals, and they will behave as you expect them to."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.2\n"
]
}
],
"source": [
"print(0.1+0.1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"However, sometimes you will get an answer with an unexpectly long decimal part:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.30000000000000004\n"
]
}
],
"source": [
"print(0.1+0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This happens because of the way computers represent numbers internally; this has nothing to do with Python itself. Basically, we are used to working in powers of ten, where one tenth plus two tenths is just three tenths. But computers work in powers of two. So your computer has to represent 0.1 in a power of two, and then 0.2 as a power of two, and express their sum as a power of two. There is no exact representation for 0.3 in powers of two, and we see that in the answer to 0.1+0.2.\n",
"\n",
"Python tries to hide this kind of stuff when possible. Don't worry about it much for now; just don't be surprised by it, and know that we will learn to clean up our results a little later on."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You can also get the same kind of result with other operations."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.30000000000000004\n"
]
}
],
"source": [
"print(3*0.1)"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test\n",
"3 * 0.1 == 0.3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The `decimal` to the rescue\n",
"\n",
"The `decimal` module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype.\n",
"For Example:\n",
"\n",
"* Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.\n",
"\n",
"\n",
"* Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.\n",
"\n",
"\n",
"* The exactness carries over into arithmetic. In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.\n",
"\n",
"\n",
"* Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem\n",
"\n",
"\n",
"* The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### See Also\n",
"\n",
"* [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)\n",
"* [`decimal` module](https://docs.python.org/3/library/decimal.html)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example using decimal"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'decimal.Decimal'>\n",
"0.30000000000000002\n",
"0.30000000000000004\n"
]
}
],
"source": [
"from decimal import Decimal, getcontext\n",
"getcontext().prec = 17\n",
"result = 3 * Decimal(0.1)\n",
"print(type(result))\n",
"print(3 * Decimal(0.1))\n",
"print(3 * 0.1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Note\n",
"\n",
"The first instruction of the previous cell is an exmaple of **selective module import**.\n",
"\n",
"So far, just note that the syntax pattern of the selective import is:\n",
" \n",
" from module import something[,something else comma separated]\n",
" \n",
"See more about this in the notebook specifically devoted to this!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_numbers'></a>Exercises\n",
"---\n",
"#### Arithmetic\n",
"- Write a program that prints out the results of at least one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.\n",
"\n",
"#### Order of Operations\n",
"- Find a calculation whose result depends on the order of operations.\n",
"- Print the result of this calculation using the standard order of operations.\n",
"- Use parentheses to force a nonstandard order of operations. Print the result of this calculation.\n",
"\n",
"#### Long Decimals\n",
"- On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.\n",
"- Find at least one other calculation that results in a long decimal like this."
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a + b = 11\n"
]
}
],
"source": [
"# Ex 2.8 : Arithmetic\n",
"a = 6\n",
"b = 5\n",
"print(\"a + b = \", end='')\n",
"o = a+b\n",
"print(o)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The result of the calculation of (3*4)+2 = 14\n"
]
}
],
"source": [
"# Ex 2.9 : Order of Operations\n",
"result = (3*4)+2\n",
"print('The result of the calculation of (3*4)+2', result, sep=' = ')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.10 : Long Decimals\n",
"print(3.125 / 0.2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='challenges_numbers'></a>Challenges\n",
"---\n",
"#### Neat Arithmetic\n",
"\n",
"- Store the results of at least 5 different calculations in separate variables. Make sure you use each operation at least once.\n",
"- Print a series of informative statements, such as \"The result of the calculation 5+7 is 12.\"\n",
"\n",
"#### Neat Order of Operations\n",
"- Take your work for \"Order of Operations\" above.\n",
"- Instead of just printing the results, print an informative summary of the results. Show each calculation that is being done and the result of that calculation. Explain how you modified the result using parentheses.\n",
"\n",
"#### Long Decimals - Pattern\n",
"- On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.\n",
"- Find a number of other calculations that result in a long decimal like this. Try to find a pattern in what kinds of numbers will result in long decimals."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Challenge: Neat Arithmetic\n",
"\n",
"# Put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Challenge: Neat Order of Operations\n",
"\n",
"# Put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Challenge: Long Decimals - Pattern\n",
"\n",
"# Put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='comments'></a>Comments\n",
"===\n",
"As you begin to write more complicated code, you will have to spend more time thinking about how to code solutions to the problems you want to solve. Once you come up with an idea, you will spend a fair amount of time troubleshooting your code, and revising your overall approach.\n",
"\n",
"Comments allow you to write in English, within your program. In Python, any line that starts with a pound (#) symbol is ignored by the Python interpreter."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This line is not a comment, it is code.\n"
]
}
],
"source": [
"# This line is a comment.\n",
"#this \n",
"#is \n",
"#not\n",
"\n",
"print(\"This line is not a comment, it is code.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='good_comments'></a>What makes a good comment?\n",
"---\n",
"- It is short and to the point, but a complete thought. Most comments should be written in complete sentences.\n",
"- It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem.\n",
"- It explains your thinking, so that others who work with your code will understand your overall approach to a problem.\n",
"- It explains particularly difficult sections of code in detail."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='when_comments'></a>When should you write a comment?\n",
"---\n",
"- When you have to think about code before writing it.\n",
"- When you are likely to forget later exactly how you were approaching a problem.\n",
"- When there is more than one way to solve a problem.\n",
"- When others are unlikely to anticipate your way of thinking about a problem.\n",
"\n",
"Writing good comments is one of the clear signs of a good programmer. If you have any real interest in taking programming seriously, start using comments now. You will see them throughout the examples in these notebooks."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_comments'></a>Exercises\n",
"---\n",
"#### First Comments\n",
"- Choose the longest, most difficult, or most interesting program you have written so far. Write at least one comment in your program.\n"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 2.10 : First Comments\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='challenges_overall'></a>Overall Challenges\n",
"===\n",
"We have learned quite a bit so far about programming, but we haven't learned enough yet for you to go create something. In the next notebook, things will get much more interesting, and there will be a longer list of overall challenges.\n",
"\n",
"<blank>\n",
"\n",
"#### What I've Learned\n",
"- Write a program that uses everything you have learned in this notebook at least once.\n",
"- Write comments that label each section of your program.\n",
"- For each thing your program does, write at least one line of output that explains what your program did.\n",
"- For example, you might have one line that stores your name with some whitespace in a variable, and a second line that strips that whitespace from your name:"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Overall Challenge\n",
"\n",
"# Put your code here"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I can strip tabs from my name: eric\n"
]
}
],
"source": [
"# I learned how to strip whitespace from strings.\n",
"name = '\\t\\teric'\n",
"print(\"I can strip tabs from my name: \" + name.strip())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
}
],
"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.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
================================================
FILE: 03 List and Tuples and Sets.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Lists Tuples and Sets"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"In this notebook, you will learn to store more than one valuable in a single variable. \n",
"\n",
"This by itself is one of the most powerful ideas in programming, and it introduces a number of other central concepts such as loops. \n",
"\n",
"If this section ends up making sense to you, you will be able to start writing some interesting programs, and you can be more confident that you will be able to develop overall competence as a programmer."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"<a name=\"top\"></a> Contents\n",
"===\n",
"- [Lists](#lists)\n",
" - [Introducing Lists](#introducing)\n",
" - [Example](#example)\n",
" - [Naming and defining a list](#naming)\n",
" - [Accessing one item in a list](#accessing_one_item)\n",
" - [Exercises](#exercises_list_introduction)\n",
" - [Lists and Looping](#looping)\n",
" - [Accessing all elements in a list](#accessing_all_elements)\n",
" - [Enumerating a list](#enumerating_list)\n",
" - [Exercises](#exercises_list_loop)\n",
" - [Common List Operations](#common_operations)\n",
" - [Modifying elements in a list](#modifying_elements)\n",
" - [Finding an element in a list](#finding_elements)\n",
" - [Testing whether an element is in a list](#testing_elements)\n",
" - [Adding items to a list](#adding_items)\n",
" - [Creating an empty list](#empty_list)\n",
" - [Sorting a list](#sorting_list)\n",
" - [Finding the length of a list](#length)\n",
" - [Exercises](#exercises_common_operations)\n",
" - [Removing Items from a List](#removing_items)\n",
" - [Removing items by position](#removing_by_position)\n",
" - [Removing items by value](#removing_by_value)\n",
" - [Popping items](#popping)\n",
" - [Exercises](#exercises_removing_items)\n",
" - [Want to see what functions are?](#functions)\n",
" - [Slicing a List](#slicing)\n",
" - [Copying a list](#copying)\n",
" - [Exercises](#exercises_slicing)\n",
" - [Numerical Lists](#numerical_lists)\n",
" - [The *range()* function](#range_function)\n",
" - [The *min()*, *max()*, *sum()* functions](#min_max_sum)\n",
" - [Exercises](#exercises_numerical)\n",
" - [List Comprehensions](#comprehensions)\n",
" - [Numerical comprehensions](#comprehensions_numerical)\n",
" - [Non-numerical comprehensions](#comprehensions_non_numerical)\n",
" - [Exercises](#exercises_comprehensions)\n",
" - [Strings as Lists](#strings_as_lists)\n",
" - [Strings as a list of characters](#list_of_characters)\n",
" - [Slicing strings](#slicing_strings)\n",
" - [Finding substrings](#finding_substrings)\n",
" - [Replacing substrings](#replacing_substrings)\n",
" - [Counting substrings](#counting_substrings)\n",
" - [Splitting strings](#splitting_strings)\n",
" - [Other string methods](#other_string_methods)\n",
" - [Exercises](#exercises_strings_as_lists)\n",
" - [Challenges](#challenges_strings_as_lists)\n",
" - [Tuples](#tuples)\n",
" - [Defining tuples, and accessing elements](#defining_tuples)\n",
" - [Using tuples to make strings](#tuples_strings)\n",
" - [Exercises](#exercises_tuples)\n",
" - [Sets](#sets)\n",
" - [Basic Operatoins on Sets](#set_operations)\n",
" - [Exercises](#exercise_set)\n",
" - [Overall Challenges](#challenges_overall)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='lists'></a>Lists\n",
"==="
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='introducing'></a>Introducing Lists\n",
"===\n",
"<a name='example'></a>Example\n",
"---\n",
"A list is a collection of items, that is stored in a variable. The items should be related in some way, but there are no restrictions on what can be stored in a list. Here is a simple example of a list, and how we can quickly access each item in the list."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Bernice!\n",
"Hello, Aaron!\n",
"Hello, Cody!\n"
]
}
],
"source": [
"students = ['bernice', 'aaron', 'cody']\n",
"\n",
"for student in students:\n",
" print(\"Hello, \" + student.title() + \"!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='naming'></a>Naming and defining a list\n",
"---\n",
"Since lists are collection of objects, it is good practice to give them a plural name. If each item in your list is a car, call the list 'cars'. If each item is a dog, call your list 'dogs'. This gives you a straightforward way to refer to the entire list ('dogs'), and to a single item in the list ('dog')."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"In Python, square brackets designate a list. To define a list, you give the name of the list, the equals sign, and the values you want to include in your list within square brackets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"dogs = ['border collie', \n",
" 'australian cattle dog', \n",
" 'labrador retriever']"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='accessing_one_item'></a>Accessing one item in a list\n",
"---\n",
"Items in a list are identified by their position in the list, starting with zero. This will almost certainly trip you up at some point. Programmers even joke about how often we all make \"off-by-one\" errors, so don't feel bad when you make this kind of error."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"To access the first element in a list, you give the name of the list, followed by a zero in parentheses."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Border Collie\n"
]
}
],
"source": [
"dogs = ['border collie', \n",
" 'australian cattle dog', \n",
" 'labrador retriever']\n",
"\n",
"dog = dogs[0]\n",
"print(dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The number in parentheses is called the **index** of the item. \n",
"\n",
"Because lists start at zero, the index of an item is always one less than its position in the list. \n",
"Because of that, **Python** is said to be a [*zero-indexed*](http://en.wikipedia.org/wiki/Zero-based_numbering) \n",
"language (as many others, like `C`, or `Java`)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"So to get the second item in the list, we need to use an index of 1, and so on.."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Australian Cattle Dog\n"
]
}
],
"source": [
"dog = dogs[1]\n",
"print(dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Accessing the last items in a list\n",
"You can probably see that to get the last item in this list, we would use an index of 2. This works, but it would only work because our list has exactly three items. To get the last item in a list, no matter how long the list is, you can use an index of -1."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Labrador Retriever\n"
]
}
],
"source": [
"dog = dogs[-1]\n",
"print(dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This syntax also works for the second to last item, the third to last, and so forth."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Australian Cattle Dog\n"
]
}
],
"source": [
"dog = dogs[-2]\n",
"print(dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"You can't use a negative number larger than the length of the list, however."
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "IndexError",
"evalue": "list index out of range",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-33-32c58df001ad>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mdogs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'border collie'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'australian cattle dog'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'labrador retriever'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mdog\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdogs\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdog\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtitle\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mIndexError\u001b[0m: list index out of range"
]
}
],
"source": [
"dog = dogs[-4]\n",
"print(dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_list_introduction'></a>Exercises\n",
"---\n",
"#### First List\n",
"- Store the values 'python', 'c', and 'java' in a list. Print each of these values out, using their position in the list.\n",
"\n",
"#### First Neat List\n",
"- Store the values 'python', 'c', and 'java' in a list. Print a statement about each of these values, using their position in the list.\n",
"- Your statement could simply be, 'A nice programming language is *value*.'\n",
"\n",
"#### Your First List\n",
"- Think of something you can store in a list. Make a list with three or four items, and then print a message that includes at least one item from your list. Your sentence could be as simple as, \"One item in my list is a ____.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.1 : First List\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.2 : First Neat List\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.3 : Your First List\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='looping'></a>Lists and Looping\n",
"==="
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='accessing_all_elements'></a>Accessing all elements in a list\n",
"---\n",
"This is one of the most important concepts related to lists. You can have a list with a million items in it, and in three lines of code you can write a sentence for each of those million items. If you want to understand lists, and become a competent programmer, make sure you take the time to understand this section.\n",
"\n",
"We use a loop to access all the elements in a list. A loop is a block of code that repeats itself until it runs out of items to work with, or until a certain condition is met. In this case, our loop will run once for every item in our list. With a list that is three items long, our loop will run three times."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Let's take a look at how we access all the items in a list, and then try to understand how it works."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"border collie\n",
"australian cattle dog\n",
"labrador retriever\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"for dog in dogs:\n",
" print(dog)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"We have already seen how to create a list, so we are really just trying to understand how the last two lines work. These last two lines make up a loop, and the language here can help us see what is happening:\n",
"\n",
" for dog in dogs:\n",
"\n",
"- The keyword \"for\" tells Python to get ready to use a loop.\n",
"- The variable \"dog\", with no \"s\" on it, is a temporary placeholder variable. This is the variable that Python will place each item in the list into, one at a time.\n",
"- The first time through the loop, the value of \"dog\" will be 'border collie'.\n",
"- The second time through the loop, the value of \"dog\" will be 'australian cattle dog'.\n",
"- The third time through, \"dog\" will be 'labrador retriever'.\n",
"- After this, there are no more items in the list, and the loop will end."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Doing more with each item\n",
"\n",
"We can do whatever we want with the value of \"dog\" inside the loop. In this case, we just print the name of the dog.\n",
"\n",
" print(dog)\n",
"\n",
"We are not limited to just printing the word dog. We can do whatever we want with this value, and this action will be carried out for every item in the list."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Let's say something about each dog in our list."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like border collies.\n",
"I like australian cattle dogs.\n",
"I like labrador retrievers.\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"for dog in dogs:\n",
" print('I like ' + dog + 's.')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Inside and outside the loop\n",
"\n",
"Python uses indentation to decide what is inside the loop and what is outside the loop. Code that is inside the loop will be run for every item in the list. Code that is not indented, which comes after the loop, will be run once just like regular code."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like border collies.\n",
"No, I really really like border collies!\n",
"\n",
"I like australian cattle dogs.\n",
"No, I really really like australian cattle dogs!\n",
"\n",
"I like labrador retrievers.\n",
"No, I really really like labrador retrievers!\n",
"\n",
"\n",
"That's just how I feel about dogs.\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"for dog in dogs:\n",
" print('I like ' + dog + 's.')\n",
" print('No, I really really like ' + dog +'s!\\n')\n",
" \n",
"print(\"\\nThat's just how I feel about dogs.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Notice that the last line only runs once, after the loop is completed. Also notice the use of newlines (\"\\n\") to make the output easier to read."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='enumerating_list'></a>Enumerating a list\n",
"---\n",
"When you are looping through a list, you may want to know the index of the current item. You could always use the *list.index(value)* syntax, but there is a simpler way. The *enumerate()* function tracks the index of each item for you, as it loops through the list:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Results for the dog show are as follows:\n",
"\n",
"Place: 0 Dog: Border Collie\n",
"Place: 1 Dog: Australian Cattle Dog\n",
"Place: 2 Dog: Labrador Retriever\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"print(\"Results for the dog show are as follows:\\n\")\n",
"for index, dog in enumerate(dogs):\n",
" place = str(index)\n",
" print(\"Place: \" + place + \" Dog: \" + dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"To enumerate a list, you need to add an *index* variable to hold the current index. So instead of\n",
"\n",
" for dog in dogs:\n",
" \n",
"You have\n",
"\n",
" for index, dog in enumerate(dogs)\n",
" \n",
"The value in the variable *index* is always an integer. If you want to print it in a string, you have to turn the integer into a string:\n",
"\n",
" str(index)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"The index always starts at 0, so in this example the value of *place* should actually be the current index, plus one:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Results for the dog show are as follows:\n",
"\n",
"Place: 1 Dog: Border Collie\n",
"Place: 2 Dog: Australian Cattle Dog\n",
"Place: 3 Dog: Labrador Retriever\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"print(\"Results for the dog show are as follows:\\n\")\n",
"for index, dog in enumerate(dogs):\n",
" place = str(index + 1)\n",
" print(\"Place: \" + place + \" Dog: \" + dog.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### A common looping error\n",
"One common looping error occurs when instead of using the single variable *dog* inside the loop, we accidentally use the variable that holds the entire list:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['border collie', 'australian cattle dog', 'labrador retriever']\n",
"['border collie', 'australian cattle dog', 'labrador retriever']\n",
"['border collie', 'australian cattle dog', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"for dog in dogs:\n",
" print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"In this example, instead of printing each dog in the list, we print the entire list every time we go through the loop. Python puts each individual item in the list into the variable *dog*, but we never use that variable. Sometimes you will just get an error if you try to do this:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "TypeError",
"evalue": "Can't convert 'list' object to str implicitly",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-20-8e7acc74d7a9>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mdog\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdogs\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'I like '\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mdogs\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m's.'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: Can't convert 'list' object to str implicitly"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"for dog in dogs:\n",
" print('I like ' + dogs + 's.')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## The FOR (iteration) loop\n",
"\n",
"The `for` loop statement is the most widely used iteration mechanisms in Python.\n",
"\n",
"* Almost every structure in Python can be iterated (*element by element*) by a `for` loop\n",
" - a list, a tuple, a dictionary, $\\ldots$ (more details will follows)\n",
"\n",
"* In Python, also `while` loops are permitted, but `for` is the one you would see (and use) most of the time!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### FOR Special keywords\n",
"\n",
"Python allows two **keywords** to be used within a `for` loop: **break** and **continue**.\n",
"\n",
"The two keywords have two **different** meanings:"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"* **Break** used to *immediatly break the loop and exit!*\n",
"* **Continue** used to *skip to the **next** iteration step!*"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"**NOTE**: The two keywords are permitted with `while` loops as well!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"## Examples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_list_loop'></a>Exercises\n",
"---\n",
"#### First List - Loop\n",
"- Repeat *First List*, but this time use a loop to print out each value in the list.\n",
"\n",
"#### First Neat List - Loop\n",
"- Repeat *First Neat List*, but this time use a loop to print out your statements. Make sure you are writing the same sentence for all values in your list. Loops are not effective when you are trying to generate different output for each value in your list.\n",
"\n",
"#### Your First List - Loop\n",
"- Repeat *Your First List*, but this time use a loop to print out your message for each item in your list. Again, if you came up with different messages for each value in your list, decide on one message to repeat for each value in your list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.4 : First List - Loop\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.5 : First Neat List - Loop\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.6 : Your First List - Loop\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='common_operations'></a>Common List Operations\n",
"==="
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='modifying_elements'></a>Modifying elements in a list\n",
"---\n",
"You can change the value of any element in a list if you know the position of that item."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['australian shepherd', 'australian cattle dog', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"dogs[0] = 'australian shepherd'\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='finding_elements'></a>Finding an element in a list\n",
"---\n",
"If you want to find out the position of an element in a list, you can use the index() function."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"print(dogs.index('australian cattle dog'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This method returns a ValueError if the requested item is not in the list."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "ValueError",
"evalue": "'poodle' is not in list",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-13-a9e05e37e8df>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mdogs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'border collie'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'australian cattle dog'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'labrador retriever'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdogs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'poodle'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: 'poodle' is not in list"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"print(dogs.index('poodle'))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='testing_elements'></a>Testing whether an item is in a list\n",
"---\n",
"You can test whether an item is in a list using the \"in\" keyword. This will become more useful after learning how to use if-else statements."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"\n",
"print('australian cattle dog' in dogs)\n",
"print('poodle' in dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='adding_items'></a>Adding items to a list\n",
"---\n",
"### Appending items to the end of a list\n",
"We can add an item to a list using the append() method. This method adds the new item to the end of the list."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Border Collies are cool.\n",
"Australian Cattle Dogs are cool.\n",
"Labrador Retrievers are cool.\n",
"Poodles are cool.\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"dogs.append('poodle')\n",
"\n",
"for dog in dogs:\n",
" print(dog.title() + \"s are cool.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Inserting items into a list\n",
"We can also insert items anywhere we want in a list, using the **insert()** function. We specify the position we want the item to have, and everything from that point on is shifted one position to the right. In other words, the index of every item after the new item is increased by one."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['border collie', 'poodle', 'australian cattle dog', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"dogs.insert(1, 'poodle')\n",
"\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Note that you have to give the position of the new item first, and then the value of the new item. If you do it in the reverse order, you will get an error."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='empty_list'></a>Creating an empty list\n",
"---\n",
"Now that we know how to add items to a list after it is created, we can use lists more dynamically. We are no longer stuck defining our entire list at once.\n",
"\n",
"A common approach with lists is to define an empty list, and then let your program add items to the list as necessary. This approach works, for example, when starting to build an interactive web site. Your list of users might start out empty, and then as people register for the site it will grow. This is a simplified approach to how web sites actually work, but the idea is realistic.\n",
"\n",
"Here is a brief example of how to start with an empty list, start to fill it up, and work with the items in the list. The only new thing here is the way we define an empty list, which is just an empty set of square brackets."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Welcome, Bernice!\n",
"Welcome, Cody!\n",
"Welcome, Aaron!\n"
]
}
],
"source": [
"# Create an empty list to hold our users.\n",
"usernames = []\n",
"\n",
"# Add some users.\n",
"usernames.append('bernice')\n",
"usernames.append('cody')\n",
"usernames.append('aaron')\n",
"\n",
"# Greet all of our users.\n",
"for username in usernames:\n",
" print(\"Welcome, \" + username.title() + '!')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"If we don't change the order in our list, we can use the list to figure out who our oldest and newest users are."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Welcome, Bernice!\n",
"Welcome, Cody!\n",
"Welcome, Aaron!\n",
"\n",
"Thank you for being our very first user, Bernice!\n",
"And a warm welcome to our newest user, Aaron!\n"
]
}
],
"source": [
"# Create an empty list to hold our users.\n",
"usernames = []\n",
"\n",
"# Add some users.\n",
"usernames.append('bernice')\n",
"usernames.append('cody')\n",
"usernames.append('aaron')\n",
"\n",
"# Greet all of our users.\n",
"for username in usernames:\n",
" print(\"Welcome, \" + username.title() + '!')\n",
"\n",
"# Recognize our first user, and welcome our newest user.\n",
"print(\"\\nThank you for being our very first user, \" + usernames[0].title() + '!')\n",
"print(\"And a warm welcome to our newest user, \" + usernames[-1].title() + '!')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Note that the code welcoming our newest user will always work, because we have used the index -1. If we had used the index 2 we would always get the third user, even as our list of users grows and grows."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='sorting_list'></a>Sorting a List\n",
"---\n",
"We can sort a list alphabetically, in either order."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Our students are currently in alphabetical order.\n",
"Aaron\n",
"Bernice\n",
"Cody\n",
"\n",
"Our students are now in reverse alphabetical order.\n",
"Cody\n",
"Bernice\n",
"Aaron\n"
]
}
],
"source": [
"students = ['bernice', 'aaron', 'cody']\n",
"\n",
"# Put students in alphabetical order.\n",
"students.sort()\n",
"\n",
"# Display the list in its current order.\n",
"print(\"Our students are currently in alphabetical order.\")\n",
"for student in students:\n",
" print(student.title())\n",
"\n",
"#Put students in reverse alphabetical order.\n",
"students.sort(reverse=True)\n",
"\n",
"# Display the list in its current order.\n",
"print(\"\\nOur students are now in reverse alphabetical order.\")\n",
"for student in students:\n",
" print(student.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### *sorted()* vs. *sort()*\n",
"Whenever you consider sorting a list, keep in mind that you can not recover the original order. If you want to display a list in sorted order, but preserve the original order, you can use the *sorted()* function. The *sorted()* function also accepts the optional *reverse=True* argument."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Here is the list in alphabetical order:\n",
"Aaron\n",
"Bernice\n",
"Cody\n",
"\n",
"Here is the list in reverse alphabetical order:\n",
"Cody\n",
"Bernice\n",
"Aaron\n",
"\n",
"Here is the list in its original order:\n",
"Bernice\n",
"Aaron\n",
"Cody\n"
]
}
],
"source": [
"students = ['bernice', 'aaron', 'cody']\n",
"\n",
"# Display students in alphabetical order, but keep the original order.\n",
"print(\"Here is the list in alphabetical order:\")\n",
"for student in sorted(students):\n",
" print(student.title())\n",
"\n",
"# Display students in reverse alphabetical order, but keep the original order.\n",
"print(\"\\nHere is the list in reverse alphabetical order:\")\n",
"for student in sorted(students, reverse=True):\n",
" print(student.title())\n",
"\n",
"print(\"\\nHere is the list in its original order:\")\n",
"# Show that the list is still in its original order.\n",
"for student in students:\n",
" print(student.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Reversing a list\n",
"We have seen three possible orders for a list:\n",
"- The original order in which the list was created\n",
"- Alphabetical order\n",
"- Reverse alphabetical order\n",
"\n",
"There is one more order we can use, and that is the reverse of the original order of the list. The *reverse()* function gives us this order."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['cody', 'aaron', 'bernice']\n"
]
}
],
"source": [
"students = ['bernice', 'aaron', 'cody']\n",
"students.reverse()\n",
"\n",
"print(students)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Note that reverse is permanent, although you could follow up with another call to *reverse()* and get back the original order of the list."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Sorting a numerical list\n",
"All of the sorting functions work for numerical lists as well."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4]\n",
"[4, 3, 2, 1]\n"
]
}
],
"source": [
"numbers = [1, 3, 4, 2]\n",
"\n",
"# sort() puts numbers in increasing order.\n",
"numbers.sort()\n",
"print(numbers)\n",
"\n",
"# sort(reverse=True) puts numbers in decreasing order.\n",
"numbers.sort(reverse=True)\n",
"print(numbers)\n"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4]\n",
"[1, 3, 4, 2]\n"
]
}
],
"source": [
"numbers = [1, 3, 4, 2]\n",
"\n",
"# sorted() preserves the original order of the list:\n",
"print(sorted(numbers))\n",
"print(numbers)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 4, 3, 1]\n"
]
}
],
"source": [
"numbers = [1, 3, 4, 2]\n",
"\n",
"# The reverse() function also works for numerical lists.\n",
"numbers.reverse()\n",
"print(numbers)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='length'></a>Finding the length of a list\n",
"---\n",
"You can find the length of a list using the *len()* function."
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron']\n",
"user_count = len(usernames)\n",
"\n",
"print(user_count)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"There are many situations where you might want to know how many items in a list. If you have a list that stores your users, you can find the length of your list at any time, and know how many users you have."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"We have 1 user!\n",
"We have 3 users!\n"
]
}
],
"source": [
"# Create an empty list to hold our users.\n",
"usernames = []\n",
"\n",
"# Add some users, and report on how many users we have.\n",
"usernames.append('bernice')\n",
"user_count = len(usernames)\n",
"\n",
"print(\"We have \" + str(user_count) + \" user!\")\n",
"\n",
"usernames.append('cody')\n",
"usernames.append('aaron')\n",
"user_count = len(usernames)\n",
"\n",
"print(\"We have \" + str(user_count) + \" users!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"On a technical note, the *len()* function returns an integer, which can't be printed directly with strings. We use the *str()* function to turn the integer into a string so that it prints nicely:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "TypeError",
"evalue": "Can't convert 'int' object to str implicitly",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-43-92e732ef190e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0muser_count\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0musernames\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"This will cause an error: \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0muser_count\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: Can't convert 'int' object to str implicitly"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron']\n",
"user_count = len(usernames)\n",
"\n",
"print(\"This will cause an error: \" + user_count)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This will work: 3\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron']\n",
"user_count = len(usernames)\n",
"\n",
"print(\"This will work: \" + str(user_count))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_common_operations'></a>Exercises\n",
"---\n",
"#### Working List\n",
"- Make a list that includes four careers, such as 'programmer' and 'truck driver'.\n",
"- Use the *list.index()* function to find the index of one career in your list.\n",
"- Use the *in* function to show that this career is in your list.\n",
"- Use the *append()* function to add a new career to your list.\n",
"- Use the *insert()* function to add a new career at the beginning of the list.\n",
"- Use a loop to show all the careers in your list.\n",
"\n",
"#### Starting From Empty\n",
"- Create the list you ended up with in *Working List*, but this time start your file with an empty list and fill it up using *append()* statements.\n",
"- Print a statement that tells us what the first career you thought of was.\n",
"- Print a statement that tells us what the last career you thought of was.\n",
"\n",
"#### Ordered Working List\n",
"- Start with the list you created in *Working List*.\n",
"- You are going to print out the list in a number of different orders.\n",
"- Each time you print the list, use a for loop rather than printing the raw list.\n",
"- Print a message each time telling us what order we should see the list in.\n",
" - Print the list in its original order.\n",
" - Print the list in alphabetical order.\n",
" - Print the list in its original order.\n",
" - Print the list in reverse alphabetical order.\n",
" - Print the list in its original order.\n",
" - Print the list in the reverse order from what it started.\n",
" - Print the list in its original order\n",
" - Permanently sort the list in alphabetical order, and then print it out.\n",
" - Permanently sort the list in reverse alphabetical order, and then print it out.\n",
"\n",
"#### Ordered Numbers\n",
"- Make a list of 5 numbers, in a random order.\n",
"- You are going to print out the list in a number of different orders.\n",
"- Each time you print the list, use a for loop rather than printing the raw list.\n",
"- Print a message each time telling us what order we should see the list in.\n",
" - Print the numbers in the original order.\n",
" - Print the numbers in increasing order.\n",
" - Print the numbers in the original order.\n",
" - Print the numbers in decreasing order.\n",
" - Print the numbers in their original order.\n",
" - Print the numbers in the reverse order from how they started.\n",
" - Print the numbers in the original order.\n",
" - Permanently sort the numbers in increasing order, and then print them out.\n",
" - Permanently sort the numbers in descreasing order, and then print them out.\n",
"\n",
"#### List Lengths\n",
"- Copy two or three of the lists you made from the previous exercises, or make up two or three new lists.\n",
"- Print out a series of statements that tell us how long each list is."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.7 : Working List\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.8 : Starting From Empty\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.9 : Ordered Working List\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.10 : Ordered Numbers\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.11 : List Lengths\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='removing_items'></a>Removing Items from a List\n",
"===\n",
"Hopefully you can see by now that lists are a dynamic structure. We can define an empty list and then fill it up as information comes into our program. To become really dynamic, we need some ways to remove items from a list when we no longer need them. You can remove items from a list through their position, or through their value."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='removing_by_position'></a>Removing items by position\n",
"---\n",
"If you know the position of an item in a list, you can remove that item using the *del* command. To use this approach, give the command *del* and the name of your list, with the index of the item you want to move in square brackets:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['australian cattle dog', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"# Remove the first dog from the list.\n",
"del dogs[0]\n",
"\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='removing_by_value'></a>Removing items by value\n",
"---\n",
"You can also remove an item from a list if you know its value. To do this, we use the *remove()* function. Give the name of the list, followed by the word remove with the value of the item you want to remove in parentheses. Python looks through your list, finds the first item with this value, and removes it."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['border collie', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"# Remove australian cattle dog from the list.\n",
"dogs.remove('australian cattle dog')\n",
"\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Be careful to note, however, that *only* the first item with this value is removed. If you have multiple items with the same value, you will have some items with this value left in your list."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['b', 'c', 'a', 'b', 'c']\n"
]
}
],
"source": [
"letters = ['a', 'b', 'c', 'a', 'b', 'c']\n",
"# Remove the letter a from the list.\n",
"letters.remove('a')\n",
"\n",
"print(letters)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='popping'></a>Popping items from a list\n",
"---\n",
"There is a cool concept in programming called \"popping\" items from a collection. Every programming language has some sort of data structure similar to Python's lists. All of these structures can be used as queues, and there are various ways of processing the items in a queue.\n",
"\n",
"One simple approach is to start with an empty list, and then add items to that list. When you want to work with the items in the list, you always take the last item from the list, do something with it, and then remove that item. The *pop()* function makes this easy. It removes the last item from the list, and gives it to us so we can work with it. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"This is easier to show with an example"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"labrador retriever\n",
"['border collie', 'australian cattle dog']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"last_dog = dogs.pop()\n",
"\n",
"print(last_dog)\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This is an example of a first-in, last-out approach. The first item in the list would be the last item processed if you kept using this approach. We will see a full implementation of this approach later on, when we learn about *while* loops.\n",
"\n",
"You can actually pop any item you want from a list, by giving the index of the item you want to pop. So we could do a first-in, first-out approach by popping the first iem in the list:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"border collie\n",
"['australian cattle dog', 'labrador retriever']\n"
]
}
],
"source": [
"dogs = ['border collie', 'australian cattle dog', 'labrador retriever']\n",
"first_dog = dogs.pop(0)\n",
"\n",
"print(first_dog)\n",
"print(dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_removing_items'></a>Exercises\n",
"---\n",
"#### Famous People\n",
"- Make a list that includes the names of four famous people.\n",
"- Remove each person from the list, one at a time, using each of the four methods we have just seen:\n",
" - Pop the last item from the list, and pop any item except the last item.\n",
" - Remove one item by its position, and one item by its value.\n",
"- Print out a message that there are no famous people left in your list, and print your list to prove that it is empty."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['david bowie', 'robert plant', 'obama']\n",
"['david bowie', 'robert plant']\n",
"david bowie ['robert plant']\n",
"there are no more famous people in the list\n",
"[]\n"
]
}
],
"source": [
"# Ex 3.12 : Famous People\n",
"fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']\n",
"#Remove each person from the list, one at a time, using each of the four methods we have just seen\n",
"fpeople.remove('taylor swift')\n",
"print(fpeople)\n",
"del fpeople[2]\n",
"print(fpeople)\n",
"bowie=fpeople.pop(0)\n",
"print(bowie,fpeople)\n",
"last=fpeople.pop()\n",
"print('there are no more famous people in the list')\n",
"print(fpeople)\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['david bowie', 'robert plant', 'obama']\n",
"['taylor swift']\n",
"['david bowie', 'robert plant']\n"
]
}
],
"source": [
"#Pop the last item from the list\n",
"fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']\n",
"fpeople.pop()\n",
"print(fpeople)\n",
"# and pop any item except the last item.\n",
"fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']\n",
"for _ in range(0,len(fpeople)-1):\n",
" fpeople.pop(0)\n",
"print(fpeople)\n",
"\n",
"fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']\n",
"fpeople.remove('obama')\n",
"del fpeople[2]\n",
"print(fpeople)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"<a name='functions'></a>Want to see what functions are?\n",
"===\n",
"At this point, you might have noticed we have a fair bit of repetetive code in some of our examples. This repetition will disappear once we learn how to use functions. If this repetition is bothering you already, you might want to go look at [Introducing Functions](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/introducing_functions.ipynb) before you do any more exercises in this section. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='slicing'></a>Slicing a List\n",
"===\n",
"Since a list is a collection of items, we should be able to get any subset of those items. For example, if we want to get just the first three items from the list, we should be able to do so easily. The same should be true for any three items in the middle of the list, or the last three items, or any x items from anywhere in the list. These subsets of a list are called *slices*."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"To get a subset of a list, we give the position of the first item we want, and the position of the first item we do *not* want to include in the subset. So the slice *list[0:3]* will return a list containing items 0, 1, and 2, but not item 3. "
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Here is how you get a batch containing the first three items."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Bernice\n",
"Cody\n",
"Aaron\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Grab the first three users in the list.\n",
"first_batch = usernames[0:3]\n",
"\n",
"for user in first_batch:\n",
" print(user.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"If you want to grab everything up to a certain position in the list, you can also leave the first index blank:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Bernice\n",
"Cody\n",
"Aaron\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Grab the first three users in the list.\n",
"first_batch = usernames[:3]\n",
"\n",
"for user in first_batch:\n",
" print(user.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"When we grab a slice from a list, the original list is not affected:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Bernice\n",
"Cody\n",
"Aaron\n",
"Ever\n",
"Dalia\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Grab the first three users in the list.\n",
"first_batch = usernames[0:3]\n",
"\n",
"# The original list is unaffected.\n",
"for user in usernames:\n",
" print(user.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"We can get any segment of a list we want, using the slice method:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cody\n",
"Aaron\n",
"Ever\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Grab a batch from the middle of the list.\n",
"middle_batch = usernames[1:4]\n",
"\n",
"for user in middle_batch:\n",
" print(user.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"To get all items from one position in the list to the end of the list, we can leave off the second index:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Aaron\n",
"Ever\n",
"Dalia\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Grab all users from the third to the end.\n",
"end_batch = usernames[2:]\n",
"\n",
"for user in end_batch:\n",
" print(user.title())"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### <a name='copying'></a>Copying a list\n",
"You can use the slice notation to make a copy of a list, by leaving out both the starting and the ending index. This causes the slice to consist of everything from the first item to the last, which is the entire list."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The full copied list:\n",
"\t ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"Two users removed from copied list:\n",
"\t ['aaron', 'ever', 'dalia']\n",
"\n",
"The original list:\n",
"\t ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n"
]
}
],
"source": [
"usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']\n",
"\n",
"# Make a copy of the list.\n",
"copied_usernames = usernames[:]\n",
"print(\"The full copied list:\\n\\t\", copied_usernames)\n",
"\n",
"# Remove the first two users from the copied list.\n",
"del copied_usernames[0]\n",
"del copied_usernames[0]\n",
"print(\"\\nTwo users removed from copied list:\\n\\t\", copied_usernames)\n",
"\n",
"# The original list is unaffected.\n",
"print(\"\\nThe original list:\\n\\t\", usernames)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_slicing'></a>Exercises\n",
"---\n",
"#### Alphabet Slices\n",
"- Store the first ten letters of the alphabet in a list.\n",
"- Use a slice to print out the first three letters of the alphabet.\n",
"- Use a slice to print out any three letters from the middle of your list.\n",
"- Use a slice to print out the letters from any point in the middle of your list, to the end.\n",
"\n",
"#### Protected List\n",
"- Your goal in this exercise is to prove that copying a list protects the original list.\n",
"- Make a list with three people's names in it.\n",
"- Use a slice to make a copy of the entire list.\n",
"- Add at least two new names to the new copy of the list.\n",
"- Make a loop that prints out all of the names in the original list, along with a message that this is the original list.\n",
"- Make a loop that prints out all of the names in the copied list, along with a message that this is the copied list."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"abcdefghijklmnopqrstuvwxyz\n",
"abcdefghij\n"
]
}
],
"source": [
"from string import ascii_lowercase\n",
"print(ascii_lowercase)\n",
"tenletters=ascii_lowercase[0:10]\n",
"print(tenletters)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"abc\n",
"ghi\n",
"ghij\n"
]
}
],
"source": [
"# Ex 3.13 : Alphabet Slices\n",
"#Store the first ten letters of the alphabet in a list.\n",
"alphabet=tenletters[:]\n",
"#Use a slice to print out the first three letters of the alphabet.\n",
"print(alphabet[:3])\n",
"#Use a slice to print out any three letters from the middle of your list.\n",
"print(alphabet[6:9])\n",
"#Use a slice to print out the letters from any point in the middle of your list, to the end.\n",
"print(alphabet[6:])\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is the original list:\n",
"Alice\n",
"Anna\n",
"Ada\n",
"This is the copy: \n",
"Alice\n",
"Anna\n",
"Ada\n",
"Agata\n",
"Aurora\n",
"['alice', 'anna', 'ada', 'agata', 'aurora']\n",
"['alice', 'anna', 'ada']\n",
"['Alice', 'Anna', 'Ada', 'Agata', 'Aurora']\n"
]
}
],
"source": [
"# Ex 3.14 : Protected List\n",
"#Your goal in this exercise is to prove that copying a list protects the original list.\n",
"#Make a list with three people's names in it.\n",
"names=['alice','anna','ada']\n",
"#Use a slice to make a copy of the entire list.\n",
"copied_names=names[:]\n",
"#Add at least two new names to the new copy of the list.\n",
"copied_names.append('agata')\n",
"copied_names.append('aurora')\n",
"#Make a loop that prints out all of the names in the original list, along with a message that this is the original list.\n",
"print('This is the original list:')\n",
"for name in names:\n",
" print(name.title())\n",
"#Make a loop that prints out all of the names in the copied list, along with a message that this is the copied list.\n",
"print('This is the copy: ')\n",
"for cname in copied_names:\n",
" print(cname.title())\n",
"print(copied_names)\n",
"\n",
"#title the names in the original list\n",
"print (names)\n",
"copied_names = [i.title() for i in copied_names]\n",
"print(copied_names)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='numerical_lists'></a>Numerical Lists\n",
"===\n",
"There is nothing special about lists of numbers, but there are some functions you can use to make working with numerical lists more efficient. Let's make a list of the first ten numbers, and start working with it to see how we can use numbers in a list."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n",
"10\n"
]
}
],
"source": [
"# Print out the first ten numbers.\n",
"numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
"\n",
"for number in numbers:\n",
" print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='range_function'></a>The *range()* function\n",
"---\n",
"This works, but it is not very efficient if we want to work with a large set of numbers. The *range()* function helps us generate long lists of numbers. Here are two ways to do the same thing, using the *range* function."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n",
"10\n"
]
}
],
"source": [
"# Print the first ten numbers.\n",
"for number in range(1,11):\n",
" print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"The range function takes in a starting number, and an end number. You get all integers, up to but not including the end number. You can also add a *step* value, which tells the *range* function how big of a step to take between numbers:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"3\n",
"5\n",
"7\n",
"9\n",
"11\n",
"13\n",
"15\n",
"17\n",
"19\n"
]
}
],
"source": [
"# Print the first ten odd numbers.\n",
"for number in range(1,21,2):\n",
" print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"If we want to store these numbers in a list, we can use the *list()* function. This function takes in a range, and turns it into a list:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
]
}
],
"source": [
"# Create a list of the first ten numbers.\n",
"numbers = list(range(1,11))\n",
"print(numbers)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This is incredibly powerful; we can now create a list of the first million numbers, just as easily as we made a list of the first ten numbers. It doesn't really make sense to print the million numbers here, but we can show that the list really does have one million items in it, and we can print the last ten items to show that the list is correct."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The list 'numbers' has 1000000 numbers in it.\n",
"\n",
"The last ten numbers in the list are:\n",
"999991\n",
"999992\n",
"999993\n",
"999994\n",
"999995\n",
"999996\n",
"999997\n",
"999998\n",
"999999\n",
"1000000\n"
]
}
],
"source": [
"# Store the first million numbers in a list.\n",
"numbers = list(range(1,1000001))\n",
"\n",
"# Show the length of the list:\n",
"print(\"The list 'numbers' has \" + str(len(numbers)) + \" numbers in it.\")\n",
"\n",
"# Show the last ten numbers:\n",
"print(\"\\nThe last ten numbers in the list are:\")\n",
"for number in numbers[-10:]:\n",
" print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"There are two things here that might be a little unclear. The expression\n",
"\n",
" str(len(numbers))\n",
"\n",
"takes the length of the *numbers* list, and turns it into a string that can be printed.\n",
"\n",
"The expression \n",
"\n",
" numbers[-10:]\n",
"\n",
"gives us a *slice* of the list. The index `-1` is the last item in the list, and the index `-10` is the item ten places from the end of the list. So the slice `numbers[-10:]` gives us everything from that item to the end of the list."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='min_max_sum'></a>The *min()*, *max()*, and *sum()* functions\n",
"---\n",
"There are three functions you can easily use with numerical lists. As you might expect, the *min()* function returns the smallest number in the list, the *max()* function returns the largest number in the list, and the *sum()* function returns the total of all numbers in the list."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Our youngest reader is 11 years old.\n",
"Our oldest reader is 38 years old.\n",
"Together, we have 149 years worth of life experience.\n"
]
}
],
"source": [
"ages = [23, 16, 14, 28, 19, 11, 38]\n",
"\n",
"youngest = min(ages)\n",
"oldest = max(ages)\n",
"total_years = sum(ages)\n",
"\n",
"print(\"Our youngest reader is \" + str(youngest) + \" years old.\")\n",
"print(\"Our oldest reader is \" + str(oldest) + \" years old.\")\n",
"print(\"Together, we have \" + str(total_years) + \n",
" \" years worth of life experience.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_numerical'></a>Exercises\n",
"---\n",
"#### First Twenty\n",
"- Use the *range()* function to store the first twenty numbers (1-20) in a list, and print them out.\n",
"\n",
"#### Larger Sets\n",
"- Take the *first\\_twenty.py* program you just wrote. Change your end number to a much larger number. How long does it take your computer to print out the first million numbers? (Most people will never see a million numbers scroll before their eyes. You can now see this!)\n",
"\n",
"#### Five Wallets\n",
"- Imagine five wallets with different amounts of cash in them. Store these five values in a list, and print out the following sentences:\n",
" - \"The fattest wallet has $ *value* in it.\"\n",
" - \"The skinniest wallet has $ *value* in it.\"\n",
" - \"All together, these wallets have $ *value* in them.\""
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n",
"10\n",
"11\n",
"12\n",
"13\n",
"14\n",
"15\n",
"16\n",
"17\n",
"18\n",
"19\n",
"20\n"
]
}
],
"source": [
"# Ex 3.15 : First Twenty\n",
"twenties=list(range(1,21))\n",
"for n in twenties:\n",
" print(n)\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"data": {
"text/plain": [
"1000000"
]
},
"execution_count": 51,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Ex 3.16 : Larger Sets\n",
"millions=list(range(0,int(1e6)))\n",
"len(millions)\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[76, 62, 53], [53, 69, 30, 5, 65, 9, 39, 75], [7, 37, 60, 64, 36, 68, 71, 88, 40], [96, 6, 15, 74, 3, 79, 54, 8, 35, 99], [1, 67, 57, 71]]\n",
"[191, 345, 471, 469, 196]\n",
"The fattest wallet has 471 in it\n",
"All together, these wallets have 1672 value in them\n",
"The thinnest wallet has 191 in it\n"
]
}
],
"source": [
"# Ex 3.17 : Five Wallets\n",
"#Imagine five wallets with different amounts of cash in them. Store these five values in a list, \n",
"#and print out the following sentences:\n",
"#\"The fattest wallet has ∗value∗init.\"−\"Theskinniestwallethas value in it.\"\n",
"#\"All together, these wallets have $ value in them.\"\n",
"\n",
"from random import randint\n",
"\n",
"wallets = [ [randint(1,100) for _ in range(randint(2,10))] for _ in range(5) ]\n",
"print(wallets)\n",
"amounts = [ sum(wallet) for wallet in wallets ]\n",
"print(amounts)\n",
"print('The fattest wallet has {} in it'.format(max(amounts)))\n",
"print('All together, these wallets have {} value in them'.format(sum(amounts)))\n",
"print('The thinnest wallet has {} in it'.format(min(amounts)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='comprehensions'></a>List Comprehensions\n",
"===\n",
"I thought carefully before including this section. If you are brand new to programming, list comprehensions may look confusing at first. They are a shorthand way of creating and working with lists. It is good to be aware of list comprehensions, because you will see them in other people's code, and they are really useful when you understand how to use them. That said, if they don't make sense to you yet, don't worry about using them right away. When you have worked with enough lists, you will want to use comprehensions. For now, it is good enough to know they exist, and to recognize them when you see them. If you like them, go ahead and start trying to use them now."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='comprehensions_numerical'></a>Numerical Comprehensions\n",
"---\n",
"Let's consider how we might make a list of the first ten square numbers. We could do it like this:"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"4\n",
"9\n",
"16\n",
"25\n",
"36\n",
"49\n",
"64\n",
"81\n",
"100\n"
]
}
],
"source": [
"# Store the first ten square numbers in a list.\n",
"# Make an empty list that will hold our square numbers.\n",
"squares = []\n",
"\n",
"# Go through the first ten numbers, square them, and add them to our list.\n",
"for number in range(1,11):\n",
" new_square = number**2\n",
" squares.append(new_square)\n",
" \n",
"# Show that our list is correct.\n",
"for square in squares:\n",
" print(square)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"This should make sense at this point. If it doesn't, go over the code with these thoughts in mind:\n",
"- We make an empty list called *squares* that will hold the values we are interested in.\n",
"- Using the *range()* function, we start a loop that will go through the numbers 1-10.\n",
"- Each time we pass through the loop, we find the square of the current number by raising it to the second power.\n",
"- We add this new value to our list *squares*.\n",
"- We go through our newly-defined list and print out each square.\n",
"\n",
"Now let's make this code more efficient. We don't really need to store the new square in its own variable *new_square*; we can just add it directly to the list of squares. The line\n",
"\n",
" new_square = number**2\n",
"\n",
"is taken out, and the next line takes care of the squaring:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"4\n",
"9\n",
"16\n",
"25\n",
"36\n",
"49\n",
"64\n",
"81\n",
"100\n"
]
}
],
"source": [
"# Store the first ten square numbers in a list.\n",
"# Make an empty list that will hold our square numbers.\n",
"squares = []\n",
"\n",
"# Go through the first ten numbers, square them, and add them to our list.\n",
"for number in range(1,11):\n",
" squares.append(number**2)\n",
" \n",
"# Show that our list is correct.\n",
"for square in squares:\n",
" print(square)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"List comprehensions allow us to collapse the first three lines of code into one line. Here's what it looks like:"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"4\n",
"9\n",
"16\n",
"25\n",
"36\n",
"49\n",
"64\n",
"81\n",
"100\n"
]
}
],
"source": [
"# Store the first ten square numbers in a list.\n",
"squares = [number**2 for number in range(1,11)]\n",
"\n",
"# Show that our list is correct.\n",
"for square in squares:\n",
" print(square)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"It should be pretty clear that this code is more efficient than our previous approach, but it may not be clear what is happening. Let's take a look at everything that is happening in that first line:\n",
"\n",
"We define a list called *squares*.\n",
"\n",
"Look at the second part of what's in square brackets:\n",
"\n",
" for number in range(1,11)\n",
"\n",
"This sets up a loop that goes through the numbers 1-10, storing each value in the variable *number*. Now we can see what happens to each *number* in the loop:\n",
"\n",
" number**2\n",
"\n",
"Each number is raised to the second power, and this is the value that is stored in the list we defined. We might read this line in the following way:\n",
"\n",
"squares = [raise *number* to the second power, for each *number* in the range 1-10]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Another example\n",
"It is probably helpful to see a few more examples of how comprehensions can be used. Let's try to make the first ten even numbers, the longer way:"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"4\n",
"6\n",
"8\n",
"10\n",
"12\n",
"14\n",
"16\n",
"18\n",
"20\n"
]
}
],
"source": [
"# Make an empty list that will hold the even numbers.\n",
"evens = []\n",
"\n",
"# Loop through the numbers 1-10, double each one, and add it to our list.\n",
"for number in range(1,11):\n",
" evens.append(number*2)\n",
" \n",
"# Show that our list is correct:\n",
"for even in evens:\n",
" print(even)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Here's how we might think of doing the same thing, using a list comprehension:\n",
"\n",
"evens = [multiply each *number* by 2, for each *number* in the range 1-10]\n",
"\n",
"Here is the same line in code:"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"4\n",
"6\n",
"8\n",
"10\n",
"12\n",
"14\n",
"16\n",
"18\n",
"20\n"
]
}
],
"source": [
"# Make a list of the first ten even numbers.\n",
"evens = [number*2 for number in range(1,11)]\n",
"\n",
"for even in evens:\n",
" print(even)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='comprehensions_non_numerical'></a>Non-numerical comprehensions\n",
"---\n",
"We can use comprehensions with non-numerical lists as well. In this case, we will create an initial list, and then use a comprehension to make a second list from the first one. Here is a simple example, without using comprehensions:"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Bernice the great!\n",
"Hello, Aaron the great!\n",
"Hello, Cody the great!\n"
]
}
],
"source": [
"# Consider some students.\n",
"students = ['bernice', 'aaron', 'cody']\n",
"\n",
"# Let's turn them into great students.\n",
"great_students = []\n",
"for student in students:\n",
" great_students.append(student.title() + \" the great!\")\n",
"\n",
"# Let's greet each great student.\n",
"for great_student in great_students:\n",
" print(\"Hello, \" + great_student)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"To use a comprehension in this code, we want to write something like this:\n",
"\n",
"great_students = [add 'the great' to each *student*, for each *student* in the list of *students*]\n",
"\n",
"Here's what it looks like:"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Bernice the great!\n",
"Hello, Aaron the great!\n",
"Hello, Cody the great!\n"
]
}
],
"source": [
"# Consider some students.\n",
"students = ['bernice', 'aaron', 'cody']\n",
"\n",
"# Let's turn them into great students.\n",
"great_students = [student.title() + \" the great!\" for student in students]\n",
"\n",
"# Let's greet each great student.\n",
"for great_student in great_students:\n",
" print(\"Hello, \" + great_student)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_comprehensions'></a>Exercises\n",
"---\n",
"If these examples are making sense, go ahead and try to do the following exercises using comprehensions. If not, try the exercises without comprehensions. You may figure out how to use comprehensions after you have solved each exercise the longer way.\n",
"\n",
"#### Multiples of Ten\n",
"- Make a list of the first ten multiples of ten (10, 20, 30... 90, 100). There are a number of ways to do this, but try to do it using a list comprehension. Print out your list.\n",
"\n",
"#### Cubes\n",
"- We saw how to make a list of the first ten squares. Make a list of the first ten cubes (1, 8, 27... 1000) using a list comprehension, and print them out.\n",
"\n",
"#### Awesomeness\n",
"- Store five names in a list. Make a second list that adds the phrase \"is awesome!\" to each name, using a list comprehension. Print out the awesome version of the names.\n",
"\n",
"#### Working Backwards\n",
"- Write out the following code without using a list comprehension:\n",
"\n",
" plus_thirteen = [number + 13 for number in range(1,11)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.18 : Multiples of Ten\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.19 : Cubes\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.20 : Awesomeness\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "skip"
}
},
"outputs": [],
"source": [
"# Ex 3.21 : Working Backwards\n",
"\n",
"# put your code here"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"[top](#top)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='strings_as_lists'></a>Strings as Lists\n",
"===\n",
"Now that you have some familiarity with lists, we can take a second look at strings. A string is really a list of characters, so many of the concepts from working with lists behave the same with strings."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='list_of_characters'></a>Strings as a list of characters\n",
"---\n",
"We can loop through a string using a *for* loop, just like we loop through a list:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"H\n",
"e\n",
"l\n",
"l\n",
"o\n",
"!\n"
]
}
],
"source": [
"message = \"Hello!\"\n",
"\n",
"for letter in message:\n",
" print(letter)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"We can create a list from a string. The list will have one element for each character in the string:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']\n"
]
}
],
"source": [
"message = \"Hello world!\"\n",
"\n",
"message_list = list(message)\n",
"print(message_list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='slicing_strings'></a>Slicing strings\n",
"---\n",
"We can access any character in a string by its position, just as we access individual items in a list:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('H', '!')\n"
]
}
],
"source": [
"message = \"Hello World!\"\n",
"first_char = message[0]\n",
"last_char = message[-1]\n",
"\n",
"print(first_char, last_char)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"We can extend this to take slices of a string:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('Hel', 'ld!')\n"
]
}
],
"source": [
"message = \"Hello World!\"\n",
"first_three = message[:3]\n",
"last_three = message[-3:]\n",
"\n",
"print(first_three, last_three)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='finding_substrings'></a>Finding substrings\n",
"---\n",
"Now that you have seen what indexes mean for strings, we can search for *substrings*. A substring is a series of characters that appears in a string.\n",
"\n",
"You can use the *in* keyword to find out whether a particular substring appears in a string:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"message = \"I like cats and dogs.\"\n",
"dog_present = 'dog' in message\n",
"print(dog_present)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"If you want to know where a substring appears in a string, you can use the *find()* method. The *find()* method tells you the index at which the substring begins."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n"
]
}
],
"source": [
"message = \"I like cats and dogs.\"\n",
"dog_index = message.find('dog')\n",
"print(dog_index)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Note, however, that this function only returns the index of the first appearance of the substring you are looking for. If the substring appears more than once, you will miss the other substrings."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n"
]
}
],
"source": [
"message = \"I like cats and dogs, but I'd much rather own a dog.\"\n",
"dog_index = message.find('dog')\n",
"print(dog_index)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"If you want to find the last appearance of a substring, you can use the *rfind()* function:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"48\n"
]
}
],
"source": [
"message = \"I like cats and dogs, but I'd much rather own a dog.\"\n",
"last_dog_index = message.rfind('dog')\n",
"print(last_dog_index)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='replacing_substrings'></a>Replacing substrings\n",
"---\n",
"You can use the *replace()* function to replace any substring with another substring. To use the *replace()* function, give the substring you want to replace, and then the substring you want to replace it with. You also need to store the new string, either in the same string variable or in a new variable."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like cats and snakes, but I'd much rather own a snake.\n"
]
}
],
"source": [
"message = \"I like cats and dogs, but I'd much rather own a dog.\"\n",
"message = message.replace('dog', 'snake')\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='counting_substrings'></a>Counting substrings\n",
"---\n",
"If you want to know how many times a substring appears within a string, you can use the *count()* method."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"message = \"I like cats and dogs, but I'd much rather own a dog.\"\n",
"number_dogs = message.count('dog')\n",
"print(number_dogs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='splitting_strings'></a>Splitting strings\n",
"---\n",
"Strings can be split into a set of substrings when they are separated by a repeated character. If a string consists of a simple sentence, the string can be split based on spaces. The *split()* function returns a list of substrings. The *split()* function takes one argument, the character that separates the parts of the string."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['I', 'like', 'cats', 'and', 'dogs,', 'but', \"I'd\", 'much', 'rather', 'own', 'a', 'dog.']\n"
]
}
],
"source": [
"message = \"I like cats and dogs, but I'd much rather own a dog.\"\n",
"words = message.split(' ')\n",
"print(words)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Notice that the punctuation is left in the substrings.\n",
"\n",
"It is more common to split strings that are really lists, separated by something like a comma. The *split()* function gives you an easy way to turn comma-separated strings, which you can't do much with in Python, into lists. Once you have your data in a list, you can work with it in much more powerful ways."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['dog', ' cat', ' tiger', ' mouse', ' liger', ' bear']\n"
]
}
],
"source": [
"animals = \"dog, cat, tiger, mouse, liger, bear\"\n",
"\n",
"# Rewrite the string as a list, and store it in the same variable\n",
"animals = animals.split(',')\n",
"print(animals)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Notice that in this case, the spaces are also ignored. It is a good idea to test the output of the *split()* function and make sure it is doing what you want with the data you are interested in.\n",
"\n",
"One use of this is to work with spreadsheet data in your Python programs. Most spreadsheet applications allow you to dump your data into a comma-separated text file. You can read this file into your Python program, or even copy and paste from the text file into your program file, and then turn the data into a list. You can then process your spreadsheet data using a *for* loop."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"<a name='other_string_methods'></a>Other string methods\n",
"---\n",
"There are a number of [other string methods](http://docs.python.org/3.3/library/stdtypes.html#string-methods) that we won't go into right here, but you might want to take a look at them. Most of these methods should make sense to you at this point. You might not have use for any of them right now, but it is good to know what you can do with strings. This way you will have a sense of how to solve certain problems, even if it means referring back to the list of methods to remind yourself how to write the correct syntax when you need it."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<a name='exercises_strings_as_lists'></a>Exercises\n",
"---\n",
"#### Listing a Sentence\n",
"- Store a single sentence in a variable. Use a for loop to print each character from your sentence on a separate line.\n",
"\n",
"#### Sentence List\n",
"- Store a single sentence in a variable. Create a list from your sentence. Print your raw list (don't use a loop, just print the list).\n",
"\n",
"#### Sentence Slices\n",
"- Store a sentence in a variable. Using slices, print out the first five characters, any five consecutive characters from the middle of the sentence, and the last five characters of the sentence.\n",
"\n",
"#### Finding Python\n",
"- Store a sentence in a variable, making sure you use the word *Python* at least twice in the sentence.\n",
"- Use the *in* keyword to prove that the word *Python* is actually in the sentence.\n",
"- Use the *find()* function to show where the word *Python* first appears in the sentence.\n",
"- Use the *rfind()* function to show the last place *Python* appears in the sentence.\n",
"- Use the *count()* function to show how many times the word *Python* appears in your sentence.\n",
"- Use the *split()* function to break your sentence into a list of words. Print the raw list, and use a loop to print each word on its own line.\n",
"- Use the *replace()* function to change *Python* to *Ruby* in your sentence."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slid
gitextract_p4ilgqem/ ├── .gitignore ├── 00 Programming Environment.ipynb ├── 01 Hello World.ipynb ├── 01 Introducing the IPython Notebook.ipynb ├── 02 Variable Strings and Numbers.ipynb ├── 03 List and Tuples and Sets.ipynb ├── 04 If Statements.ipynb ├── 05 While Loops and User input.ipynb ├── 06 Dictionaries.ipynb ├── 07 Introduction to Functions.ipynb ├── 07 More Functions.ipynb ├── 08 Classes and OOP.ipynb ├── 09 Exceptions.ipynb ├── 10 External files.ipynb ├── 11 Persistence.ipynb ├── Coding Style (PEP8).ipynb ├── Importing Modules.ipynb ├── Index.ipynb ├── LICENSE ├── README.md ├── Resources and References.ipynb ├── The Zen of Python.ipynb ├── data/ │ ├── data.txt │ ├── data2.txt │ ├── dbase1 │ ├── elderlyHeightWeight.csv │ ├── male_data.tsv │ ├── new_data.csv │ ├── test.txt │ └── testdb ├── files/ │ ├── example.css │ └── makedicts.py ├── multiplying.py └── rocket.py
SYMBOL INDEX (10 symbols across 3 files)
FILE: files/makedicts.py
function makedicts (line 6) | def makedicts(cursor, query, params=()):
FILE: multiplying.py
function double (line 3) | def double(x):
function triple (line 6) | def triple(x):
function quadruple (line 9) | def quadruple(x):
FILE: rocket.py
class Rocket (line 3) | class Rocket():
method __init__ (line 7) | def __init__(self, x=0, y=0):
method move_rocket (line 12) | def move_rocket(self, x_increment=0, y_increment=1):
method get_distance (line 18) | def get_distance(self, other_rocket):
class Shuttle (line 25) | class Shuttle(Rocket):
method __init__ (line 29) | def __init__(self, x=0, y=0, flights_completed=0):
Condensed preview — 34 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (791K chars).
[
{
"path": ".gitignore",
"chars": 384,
"preview": "TOC.ipynb\n__pycache__\ndata/BODY_COMPOSITION_DATA_4_ASSIGNMENT.csv\ndata/BODY_COMPOSITION_DATA_4_ASSIGNMENT.tsv\ndata/elder"
},
{
"path": "00 Programming Environment.ipynb",
"chars": 3150,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Programming Environment\\n\",\n \""
},
{
"path": "01 Hello World.ipynb",
"chars": 1554,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "01 Introducing the IPython Notebook.ipynb",
"chars": 35201,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "02 Variable Strings and Numbers.ipynb",
"chars": 46441,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "03 List and Tuples and Sets.ipynb",
"chars": 136983,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "04 If Statements.ipynb",
"chars": 41886,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "05 While Loops and User input.ipynb",
"chars": 36432,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "06 Dictionaries.ipynb",
"chars": 84841,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "07 Introduction to Functions.ipynb",
"chars": 29838,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "07 More Functions.ipynb",
"chars": 49649,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "08 Classes and OOP.ipynb",
"chars": 97026,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "09 Exceptions.ipynb",
"chars": 12794,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Exceptions\"\n ]\n },\n {\n \"cel"
},
{
"path": "10 External files.ipynb",
"chars": 54158,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "11 Persistence.ipynb",
"chars": 29769,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Persistence\"\n ]\n },\n {\n \"ce"
},
{
"path": "Coding Style (PEP8).ipynb",
"chars": 12247,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "Importing Modules.ipynb",
"chars": 17432,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "Index.ipynb",
"chars": 2298,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"Introduction to Python\\n\",\n \"==="
},
{
"path": "LICENSE",
"chars": 1082,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Valerio Maggio\n\nPermission is hereby granted, free of charge, to any person ob"
},
{
"path": "README.md",
"chars": 1905,
"preview": "# Python in a Notebook #\n\nThis repository contains a curated collection of Jupyter/IPython Notebooks of \nintroductory ma"
},
{
"path": "Resources and References.ipynb",
"chars": 6842,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# References\"\n ]\n },\n {\n \"cel"
},
{
"path": "The Zen of Python.ipynb",
"chars": 5421,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"slideshow\": {\n \"slide_type\": \"slide\"\n }\n },"
},
{
"path": "data/data.txt",
"chars": 79,
"preview": "bob,devel,50000\nsue,music,60000\nann,devel,40000\ntim,admin,30000\nkim,devel,60000"
},
{
"path": "data/data2.txt",
"chars": 53,
"preview": "bob,developer,80000\nsue,music,90000\nann,manager,80000"
},
{
"path": "data/elderlyHeightWeight.csv",
"chars": 286,
"preview": "Gender\tAge\tbody wt\tht\nF\t77\t63.8\t155.5\nF\t80\t56.4\t160.5\nF\t76\t55.2\t159.5\nF\t77\t58.5\t151\nF\t82\t64\t165.5\nF\t78\t51.6\t167\nF\t85\t54."
},
{
"path": "data/male_data.tsv",
"chars": 148,
"preview": "M\t79\t75.5\t171\nM\t75\t83.9\t178.5\nM\t79\t75.7\t167\nM\t84\t72.5\t171.5\nM\t76\t56.2\t167\nM\t80\t73.4\t168.5\nM\t75\t67.7\t174.5\nM\t75\t93\t168\nM\t"
},
{
"path": "data/new_data.csv",
"chars": 390,
"preview": "Gender\tAge\tbody wt\tht\tht_m\nF\t77\t63.8\t155.5\t1.555\nF\t80\t56.4\t160.5\t1.605\nF\t76\t55.2\t159.5\t1.595\nF\t77\t58.5\t151\t1.51\nF\t82\t64\t"
},
{
"path": "data/test.txt",
"chars": 70,
"preview": "Line 0\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\n"
},
{
"path": "files/example.css",
"chars": 2895,
"preview": "<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400ital"
},
{
"path": "files/makedicts.py",
"chars": 509,
"preview": "\"\"\"\nconvert list of row tuples to list of row dicts with field name keys\n\"\"\"\nimport sqlite3\n\ndef makedicts(cursor, query"
},
{
"path": "multiplying.py",
"chars": 121,
"preview": "# Save as multiplying.py\n\ndef double(x):\n return 2*x\n\ndef triple(x):\n return 3*x\n\ndef quadruple(x):\n return 4*x"
},
{
"path": "rocket.py",
"chars": 1006,
"preview": "from math import sqrt\n\nclass Rocket():\n # Rocket simulates a rocket ship for a game,\n # or a physics simulation.\n"
}
]
// ... and 2 more files (download for full content)
About this extraction
This page contains the full source code of the leriomaggio/python-in-a-notebook GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 34 files (696.2 KB), approximately 209.7k tokens, and a symbol index with 10 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.