Commit 5ca4d9f2 authored by Arucas Chacon's avatar Arucas Chacon

Completed notebooks

parent 2820c217
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Jupyter Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![jupyter](images/jupyter-logo-2.png)\n",
"\n",
"![IPython](images/ipython_logo-s.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How can I run Python programs?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* **.py** extension, plain-text Python programs. \n",
"* **.ipynb** extension to distinguish them from plain-text Python programs. We'll be able to mix: **code, documentation and graphics** in the same file. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Jupyter Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <a href=\"https://docs.anaconda.com/anaconda/install/\" target=\"_blank\">Anaconda package manager</a> is an automated way to install the Jupyter notebook.\n",
"* See the <a href=\"https://swcarpentry.github.io/python-novice-gapminder/setup/\"> setup instructions</a> for Anaconda installation instructions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can start the notebook server from the command line (Terminal on Mac/Linux, CMD prompt on Windows) by running the following command: \n",
"\n",
" <div class=\"alert alert-info\" role=\"alert\">jupyter-notebook</div> \n",
"\n",
"This will print some information about the notebook server in your terminal, including the URL of the web application (by default, `http://127.0.0.1:8888`). It will then open your default web browser to this URL.\n",
"\n",
"When the notebook opens, you will see the **notebook dashboard**, which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. This will be your work directory."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Open a new notebook from the dropdown menu (that says ‘New’) in the top right corner of the file browser page.\n",
"* Each notebook contains one or more cells that contain code, text, or images."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modal editor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Jupyter Notebooks have 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": {},
"source": [
"* If you press “ESC” and “ENTER” alternately, the outer border of your code cell will change from grey/blue to green.\n",
"* These are the <span class=\"label label-info\">command (grey/blue)</span> and <span class=\"label label-success\">edit (green)</span>\n",
" modes of your notebook.\n",
"\n",
"* Command mode allows you to edit notebook-level features, and edit mode changes the content of cells.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Edit mode\n",
"\n",
"Edit mode is indicated by a green cell border and a prompt showing in the editor area:\n",
"\n",
"<img src=\"images/edit_mode.png\">\n",
"\n",
"When a cell is in edit mode, you can type into the cell, like a normal text editor.\n",
"\n",
"<div class=\"alert alert-success\">\n",
"Enter edit mode by pressing `ENTER` or using the mouse to click on a cell's editor area.\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = 10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Command mode\n",
"\n",
"Command mode is indicated by a grey cell border with a blue left margin:\n",
"\n",
"<img src=\"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.\n",
"\n",
"* In <span class=\"label label-info\">command mode</span>, pressing the “H” key will provide a list of all the shortcut keys.\n",
"\n",
"* When in <span class=\"label label-info\">command mode</span> (ESC/grey):\n",
" * The “B” key will make a new cell below the currently selected cell.\n",
" * The “A” key will make one above.\n",
" * The “X” key will delete the current cell.\n",
" * The “Z” key will undo your last cell deletion.\n",
" * The “M” key will will set the current cell as a Markdown cell.\n",
" * The “Y” key will will set the current cell as a Code cell.\n",
"* All actions can be done using the menus, but there are lots of keyboard shortcuts to speed things up.\n",
"\n",
"<div class=\"alert alert-danger\">\n",
"Don't try to type into a cell in command mode; unexpected things will happen!\n",
"</div>\n",
"\n",
"<div class=\"alert alert-success\">\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": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - (2 mins)</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" - In the Jupyter notebook, are you currently in command or edit mode? <br>\n",
" - Switch between the modes. Use the shortcuts to generate a new cell. Use the shortcuts to delete a cell\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cell types"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have different types of cells. The type of a cell is selected from the dropdown menu or with a keyboard shortcut in command mode. We'll see `code` cells and `Markdown` cells. \n",
"\n",
"This is a **Markdown** cell itself and is used to add formatted text to your notebooks. You can use both [Markdown](https://en.wikipedia.org/wiki/Markdown) syntax and [LaTeX](https://en.wikipedia.org/wiki/LaTeX) syntax.\n",
"\n",
"You can include mathematical expressions both inline: $e^{i\\pi} + 1 = 0$ and displayed:\n",
"\n",
"$$e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Code cells** on the other hand allow us to input Python code which will be later run by the kernel. \n",
"\n",
"Run a code cell using `Shift-Enter` or pressing the <button class='btn btn-default btn-xs'><i class=\"icon-play fa fa-play\"></i></button> button in the toolbar above. Once the cell is run (see below how), the corresponding output, if any, apperas below the cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This is a code cell. It runs code :-)\n",
"a = [1., 4., 3.14]\n",
"print (a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# And another code cell\n",
"a = 10\n",
"b= 2\n",
"a/b"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# a third one\n",
"a+b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"$e^x$\n",
"\n",
"$$e^x$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running cells\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The keyboard shortcuts for running a cell, both in edit and command mode, are:\n",
"\n",
"* `Shift-Enter` runs the current cell and moves to the one below.\n",
"* `Alt-Enter` runs the current cell and inserts a new one below.\n",
"* `Ctrl-Enter` run the current cell and enters command mode in current cell.\n",
"\n",
"<div class=\"alert alert-success\">\n",
"Press `h` anytime in command mode for a keyboard shotcut list.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tab completion & help (edit mode)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Tab completion**, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type in a code cell `object_name.<TAB>` to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.\n",
"\n",
"For getting an object **help**, type `object_name.<SHIFT+TAB>` and a tooltip with the object short help will open. Pressing `<TAB>` twice (`<SHIFT+TAB+TAB>`) the full object help will open. Doing it four times and the full object help will go into a new frame."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"\n",
"\n",
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li><span class=\"label label-info\">command (grey/blue)</span> (for the whole notebook, press `ESC`) and <span class=\"label label-success\">edit (green)</span> (for a cell, `ENTER`) modes.</li>\n",
" <li>If you remember the “ESC” and “h” shortcut, you will be able to find out all the rest.</li>\n",
" <li>A Jupyter **notebook** is composed by **cells**.</li>\n",
" <li>Cells can be **Markdown** (text cells accepting Markdown and LaTeX syntax), and **code** cells (for executing code).</li>\n",
" <li>Use tab completion (`object_name.TAB`) and inline help (`object_name.SHIFT+TAB`) extensively.</li>\n",
" </ul>\n",
"</div>\n",
"</div>\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## References \n",
"* [IAMC's github](https://github.com/iamc/2017-06-28-cfmehu-ScientificPython/blob/master/jupyter-quickstart.ipynb).\n",
"\n",
"* This tutorial was essentially based in [IPython's notebook-based documentation](http://nbviewer.ipython.org/github/ipython/ipython/blob/3.x/examples/Index.ipynb). Take a look at it for a more extensive introduction to IPython.\n",
"\n",
"* Official [Jupyter notebook begginer guide](http://jupyter-notebook-beginner-guide.readthedocs.org/en/latest/index.html#).\n",
"\n",
"* Official [Jupyter user manual](https://jupyter.readthedocs.io/en/latest/index.html)\n",
"\n",
"* [A gallery of interesting IPython Notebooks](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks).\n",
"\n",
"* [IPython project page](http://ipython.org/)\n",
"\n",
"* [Jupyter project page](http://jupyter.org/)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Variables and assignment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use variables to store values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Variables are names for values.\n",
"* In Python the = symbol assigns the value on the right to the name on the left.\n",
"* The variable is created when a value is assigned to it.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"weight_kg = 55"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Variable names:\n",
" * can’t start with a digit\n",
" * can’t contain spaces, quotation marks, or other punctuation\n",
" * may contain an underscore (typically used to separate words in long variable names)\n",
"* Underscores at the start like __alistairs_real_age have a special meaning so we won’t do that until we understand the convention."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use print to display values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Python has a built-in function called <span class=\"label label-default\">print</span> that prints things as text.\n",
"* To add a string to the printout, wrap the string in single quotations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(weight_kg)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('weight in kg:', weight_kg)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables must be created before they are used."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(last_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\" role=\"alert\">\n",
"Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook does\n",
"not matter (i.e., cells lower down can still affect those above). Remember: Notebook cells are just a way to organize a program: as far as Python is concerned, all of the source code is one long set of instructions.\n",
"</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables can be used in calculations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('weight in pounds:', 2.2 * weight_kg)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"weight_lb = 2.2 * weight_kg\n",
"print('weight in kilograms:', weight_kg, 'and in pounds:', weight_lb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use an index to get a single character from a string.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Strings are lists of characters.\n",
"* <span class=\"label label-success\">Indices start numbered from 0</span>.\n",
"* Use the position’s index in square brackets to get the character at that position."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"workshop_name = 'Software carpentry'\n",
"print(workshop_name)\n",
"print('the first character is',workshop_name[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use a slice to get a substring.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* A part of a string is called a substring. A substring can be as short as a single character.\n",
"* We take a slice of a string by using <span class=\"label label-default\">[start:stop]</span>, where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want.\n",
"* Mathematically, you might say that a slice selects [start:stop), from start to stop-1\n",
"* Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(workshop_name[0:6])\n",
"print(workshop_name[2:10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function len to find the length of a string.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(len(workshop_name))\n",
"print(len(workshop_name[1:6]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python is case-sensitive."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Python thinks that upper- and lower-case letters are different, so <span class=\"label label-default\">Name</span> and <span class=\"label label-default\">name</span> are different variables.\n",
"* There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use meaningful variable names."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"qwert = 55\n",
"poiu = \"Arucas'\"\n",
"print (poiu, 'weight is', qwert)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Swapping Values</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill the table showing the values of the variables in this program after each statement is executed.\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Command # Value of x # Value of y # Value of swap #\n",
"x = 1.0 # # # #\n",
"y = 3.0 # # # #\n",
"swap = x # # # #\n",
"x = y # # # #\n",
"y = swap # # # #"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Predicting Values</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"What is the final value of <span class=\"label label-default\">position</span> in the program below? (Try to predict the value without running the program, then check your prediction.)\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"initial = \"left\"\n",
"position = initial\n",
"initial = \"right\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Choosing a name</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"Which is a better variable name, <span class=\"label label-default\">m</span>, <span class=\"label label-default\">min</span>, or <span class=\"label label-default\">minutes</span>? Why? Hint: think about which code you would rather inherit from someone who is leaving the lab:\n",
"\n",
" </div>\n",
"</div>\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"ts = m * 60 + s\n",
"tot_sec = min * 60 + sec\n",
"total_seconds = minutes * 60 + seconds"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Use variables to store values.</li>\n",
" <li>Use print to display values.</li>\n",
" <li>Variables persist between cells.</li>\n",
" <li>Variables must be created before they are used.</li>\n",
" <li>Variables can be used in calculations.</li>\n",
" <li>Use an index to get a single character from a string.</li>\n",
" <li>Use a slice to get a substring.</li>\n",
" <li>Use the built-in function len to find the length of a string.</li>\n",
" <li>Python is case-sensitive.</li>\n",
" <li>Use meaningful variable names.</li> \n",
" </ul> \n",
"</div>\n",
"</div>"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data Types and Type Conversion\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every value has a type."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every value in a program has a specific type.\n",
"* For instance: integer,float, string\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"age = 32\n",
"pi = 3.14\n",
"first_name = 'Arucas'\n",
"print(age)\n",
"print(pi)\n",
"print(first_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function type to find the type of a value.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(type(age))\n",
"print(type(pi))\n",
"print(type(first_name))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Types control what operations (or methods) can be performed on a given value.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(5-2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('hello' - 'h')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## You can use the “+” and “*” operators on strings.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"full_name = 'Arucas' + ' ' + 'Chacon'\n",
"print(full_name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"separator = '=' * 10\n",
"print(separator)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strings have a length (but numbers don’t)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(len(full_name))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(len(pi))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Must convert numbers to strings or vice versa when operating on them.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(1 + '2')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"print(1 + int('2'))\n",
"print(str(1) + '2')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"string to float:\", float(\"3.4\"))\n",
"print(\"float to int:\", int(3.9))\n",
"print(\"int to float:\", float(3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Can mix integers and floats freely in operations.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('half is', 1 / 2.0)\n",
"print('three squared is', 3.0 ** 2)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Complex numbers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python provides complex numbers, which are written as <span class=\"label label-default\">1.0+2.0j</span>. If val is an imaginary number, its real and imaginary parts can be accessed using dot notation as <span class=\"label label-default\">val.real</span> and <span class=\"label label-default\">val.imag</span>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"val = 1.0+2.0j\n",
"print(val.real)\n",
"print(val.imag)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" What type of value is 3.4?<br>\n",
" What type of value is 3.25 + 4?<br>\n",
" What type of value is 4/2?<br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Division Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"In Python 3, the // operator performs integer (whole-number) floor division, the / operator performs floating-point division, and the ‘%’ (or modulo) operator calculates and returns the remainder from integer division.<br>\n",
"\n",
"However in Python2 (and other languages), the / operator between two integer types perform a floor (//) division. To perform a float division, we have to convert one of the integers to float\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('5 // 3 =', 5//3)\n",
"print('5 / 3 =', 5/3)\n",
"print('5 % 3 =', 5%3)\n",
"print('float(5)/3 =', float(5) / 3 )\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"\n",
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Arithmetic with Different Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Which of the following will print 2.0? Note: there may be more than one right answer.<br>\n",
" first = 1.0<br>\n",
"second = \"1\"<br>\n",
"third = \"1.1\"<br>\n",
"<br> \n",
"<br> \n",
"1. first + float(second)<br>\n",
"2. float(second) + float(third)<br>\n",
"3. first + int(third)<br>\n",
"4. first + int(float(third))<br>\n",
"5. int(first) + int(float(third))<br>\n",
"6. 2.0 * second\n",
" </div>\n",
"</div>\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"first = 1.0\n",
"second = \"1\"\n",
"third = \"1.1\"\n",
"\n",
"first + float(second)\n",
"float(second) + float(third)\n",
"#first + int(third)\n",
"first + int(float(third))\n",
"int(first) + int(float(third))\n",
"2.0 * second"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Every value has a type.</li>\n",
" <li>Use the built-in function <span class=\"label label-default\">type()</span> to find the type of a value.</li>\n",
" <li>Types control what operations can be done on values.</li>\n",
" <li>Strings can be added and multiplied.</li>\n",
" <li>Strings have a length (but numbers don’t).</li>\n",
" <li>Must convert numbers to strings or vice versa when operating on them.</li>\n",
" <li>Must convert numbers to strings or vice versa when operating on them.</li>\n",
" <li>Can mix integers and floats freely in operations.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Built-in Functions and Help"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Use comments to add documentation to programs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# This is a comment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A function may take zero or more arguments.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* We've alreadys een some built-in functions\n",
"* print(), len(), int(), float(), str()\n",
"* Always with parenthesis, even if empty"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Commonly-used built-in functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* max() , min()\n",
"* round(), will round off a floating-point number.By default, rounds to zero decimal places."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"max(1,100,2000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"min(1,100,2000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(3.712)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(2.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(3.712, 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function <span class=\"label label-default\">help</span> to get help for a function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every built-in function has online documentation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"help(round)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Jupyter Notebook has two ways to get help.\n",
"* Place the cursor inside the parenthesis of the function, hold down shift, and press tab.\n",
"* Or type a function name with a question mark after it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"round()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every function returns something.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every function call produces some result.\n",
"* If the function doesn’t have a useful result to return, it usually returns the special value None."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"result = print('example')\n",
"print('result of print is', result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Use comments to add documentation to programs.</li>\n",
" <li>A function may take zero or more arguments.</li>\n",
" <li>Commonly-used built-in functions include max, min, and round.</li>\n",
" <li>Functions may have default values for some arguments.</li>\n",
" <li>Use the built-in function help to get help for a function.</li>\n",
" <li>The Jupyter Notebook has two ways more to get help.</li>\n",
" <li>Every function returns something.</li>\n",
" </ul> \n",
"</div>\n",
"</div>"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lists"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A list stores many values in a single structure.\n",
"* Use a list to store many values together.\n",
"* Contained within square brackets [...].\n",
"* Values separated by commas ,.\n",
"* Use <span class=\"label label-default\">len</span> to find out how many values are in a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"pressures = [0.273, 0.275, 0.277, 0.275, 0.276]\n",
"print('pressures:', pressures)\n",
"print('length:', len(pressures))\n",
"type(pressures)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use an item’s index to fetch it from a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('zeroth item of pressures:', pressures[0])\n",
"print('fourth item of pressures:', pressures[4])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lists’ values can be replaced by assigning to them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"pressures[0] = 0.265\n",
"print('pressures is now:', pressures)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Appending items\n",
"* Use <span class=\"label label-default\">list_name.append</span> to add items to the end of a list.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"primes = [2, 3, 5]\n",
"print('primes is initially:', primes)\n",
"primes.append(7)\n",
"primes.append(9)\n",
"print('primes has become:', primes)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* <span class=\"label label-default\">append</span> is a method of lists.\n",
" * Like a function, but tied to a particular object.\n",
"* Use <span class=\"label label-default\">object_name.method_name</span> to call methods.\n",
"* Use <span class=\"label label-default\">help(list)</span> for a preview.\n",
"* <span class=\"label label-default\">extend</span> is similar to append, but it allows you to combine two lists. For example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"teen_primes = [11, 13, 17, 19]\n",
"middle_aged_primes = [37, 41, 43, 47]\n",
"print('primes is currently:', primes)\n",
"primes.extend(teen_primes)\n",
"print('primes with extend has now become:', primes)\n",
"primes.append(middle_aged_primes)\n",
"print('primes with append has finally become:', primes)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Note that while `extend` maintains the \"flat\" structure of the list, appending a list to a list makes the result two-dimensional.\n",
"\n",
"## Use `del` to remove items from a list entirely.\n",
"\n",
"* `del list_name[index]` removes an item from a list and shortens the list.\n",
"* Not a function or a method, but a statement in the language.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('primes before removing last item:', primes) \n",
"del primes[4] \n",
"print(\"primes after removing last item:\", primes)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The empty list contains no values.\n",
"\n",
"* Use `[]` on its own to represent a list that doesn't contain any values.\n",
" * \"The zero of lists.\"\n",
"* Helpful as a starting point for collecting values\n",
" (which we will see in the next episode)\n",
"\n",
"## Lists may contain values of different types.\n",
"\n",
"* A single list may contain numbers, strings, and anything else."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Character strings can be indexed like lists.\n",
"\n",
"* Get single characters from a character string using indexes in square brackets.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"element = 'carbon' \n",
"print('zeroth character:', element[0]) \n",
"print('third character:', element[3])\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Character strings are immutable.\n",
"\n",
"* Cannot change the characters in a string after it has been created.\n",
" * *Immutable*: can't be changed after creation.\n",
" * In contrast, lists are *mutable*: they can be modified in place.\n",
"* Python considers the string to be a single value with parts,\n",
" not a collection of values.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"element[0] = 'C'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
" Lists and character strings are both *collections*.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Indexing beyond the end of the collection is an error.\n",
"\n",
"* Python reports an `IndexError` if we attempt to access a value that doesn't exist.\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": false
},
"outputs": [],
"source": [
"print('99th element of element is:', element[99])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strides"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* If we write a slice as [low:high:stride], what does stride do?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"element = 'fluorine'\n",
"print(element[::2]) #even-numbered items 0,2\n",
"print(element[1::2])#odd-numbered items\n",
"print(element[::-1])#backwards, from the last position to the first position\n",
"print(element[::1])#fordward\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Fill in the Blanks</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"values = ____\n",
"values.____(1)\n",
"values.____(3)\n",
"values.____(5)\n",
"print('first time:', values)\n",
"values = values[____]\n",
"print('second time:', values)\n",
"\n",
"---RESULT---\n",
"first time: [1, 3, 5]\n",
"second time: [3, 5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - How Large is a Slice?</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"If ‘low’ and ‘high’ are both non-negative integers, how long is the list values[low:high]?\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Nested Lists</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = [['pepper', 'zucchini', 'onion'],\n",
" ['cabbage', 'lettuce', 'garlic'],\n",
" ['apple', 'pear', 'banana']]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Nested_lists](images/indexing_lists_python.png)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print([x[0]])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x[0][0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>A list stores many values in a single structure..</li>\n",
" <li>Use an item’s index to fetch it from a list.</li>\n",
" <li>Lists’ values can be replaced by assigning to them. </li>\n",
" <li>Appending items to a list lengthens it.</li>\n",
" <li>Use <span class=\"label label-default\">del</span> to remove items from a list entirely.</li>\n",
" <li>The empty list contains no values.</li>\n",
" <li>Lists may contain values of different types.</li>\n",
" <li>Character strings can be indexed like lists.</li>\n",
"<li>Character strings are <span class=\"label label-default\">immutable</span>.</li>\n",
"<li>Indexing beyond the end of the collection is an error.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# For loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A for loop run commands once for each value in a collection.\n",
"* Doing calculations on the values in a list one by one is painful, imaging with 1000 items!!! UNFEASIBLE!!! :(\n",
"* A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.\n",
"* “for each thing in this group, do these operations”\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![For loop](images/loops_image.png)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"word = 'oxigen'\n",
"for char in word:\n",
" print(char)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A for loop is made up of a collection, a loop variable, and a body."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* The loop variable, number, is what changes for each iteration of the loop and can be called anything.\n",
"\n",
"* The collection, [2, 3, 5], is what the loop is being run on.\n",
"* The body, print(number), specifies what to do for each value in the collection and can contain many statements.\n",
"* The first line of the for loop must end with a <span class=\"label label-default\">colon</span>, and the body must be <span class=\"label label-default\">indented</span>.\n",
"* The colon at the end of the first line signals the start of a block of statements.\n",
"* Python uses indentation (typically 4 spaces) rather than {} or begin/end to show nesting.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for number in [2,3,5]:\n",
" print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for number in [2,3,5]:\n",
"print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"first_name=\"Jonh\"\n",
" last_name=\"Smith\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use <span class=\"label label-default\">range</span> to iterate over a sequence of numbers.\n",
"* The built-in function range produces a sequence of numbers.\n",
"* range(N) is the numbers 0..N-1, the length N"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for number in range(3):\n",
" print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"for number in range(1,10):\n",
" print(number, end= \" \")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"for number in range(1,10,2):\n",
" print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Accumulator pattern turns many values into one.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* A common pattern in programs is to:\n",
" * Initialize an accumulator variable to zero, the empty string, or the empty list.\n",
" * Update the variable with values from a collection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Sum the first 10 integers.\n",
"total = 0\n",
"for number in range(10):\n",
" total = total + (number + 1)\n",
" #print(total)\n",
"print(total)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Squared and cubed prime numbers</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" We have a list of prime numbers, and we want to calculate the squared and cubed numbers for every prime number.\n",
" <br>\n",
"\n",
" </div>\n",
"</div>\n",
" \n",
" "
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"#Solution\n",
"primes = [2, 3, 5]\n",
"for p in primes:\n",
" squared = p ** 2\n",
" cubed = p ** 3\n",
" print(p, squared, cubed)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Reverse a string</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill in the blanks in the program below so that it prints “nit” (the reverse of the original character string “tin”).<br><br>\n",
" </div>\n",
"</div>\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"original = \"theoretical physics\"\n",
"result = ____\n",
"for char in original:\n",
" result = ____\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution\n",
"original = \"theoretical physics\"\n",
"result = \"\"\n",
"for char in original:\n",
" result = char + result\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Practice Accumulating</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill in the blanks in each of the programs below to produce the indicated result.<br><br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Total length of the strings in the list: [\"red\", \"green\", \"blue\"] => 12\n",
"total = 0\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" ____ = ____ + len(word)\n",
"print(total)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# List of word lengths: [\"red\", \"green\", \"blue\"] => [3, 5, 4]\n",
"lengths = ____\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" lengths.____(____)\n",
"print(lengths)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Concatenate all words: [\"red\", \"green\", \"blue\"] => \"redgreenblue\"\n",
"words = [\"red\", \"green\", \"blue\"]\n",
"result = ____\n",
"for ____ in ____:\n",
" ____\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution\n",
"total = 0\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" total = total + len(word)\n",
"print(total)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution\n",
"lengths = []\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" lengths.append(len(word))\n",
"print(lengths)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#solution\n",
"words = [\"red\", \"green\", \"blue\"]\n",
"result = \"\"\n",
"for word in words:\n",
" result = result + word\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>A <span class=\"label label-default\">for</span> loop runs commands once for each value in a collection.</li>\n",
"<li>The first line of the <span class=\"label label-default\">for</span> loop must end with a colon, and the body must be indented.</li>\n",
"<li><span class=\"label label-default\">Indentation</span> is always meaningful in Python.</li>\n",
"<li>A for loop is made up of a collection, a loop variable, and a body.</li>\n",
"<li>Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).</li>\n",
"<li>The body of a loop can contain many statements.</li>\n",
"<li>Use <span class=\"label label-default\">range</span> to iterate over a sequence of numbers.</li>\n",
"<li>The Accumulator pattern turns many values into one.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Writing Functions\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Break programs down into functions to make them easier to understand."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Functions are reusable, self-contained pieces of code that are called with a single command. \n",
"* They can be designed to accept arguments as input and return values, but they don’t need to do either. \n",
"* Variables declared inside functions only exist while the function is running and if a variable within the function (a local variable) has the same name as a variable somewhere else in the code, the local variable hides but doesn’t overwrite the other.\n",
"* Every method used in Python (for example, print) is a function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Define a function using def with a name, parameters, a colon and a block of indented code."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![jupyter](images/python-function.svg)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"#http://www.rapidtables.com/convert/temperature/fahrenheit-to-kelvin.htm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def fahr_to_kelvin(temp):\n",
" return ((temp - 32) * (5/9) + 273.15) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('freezing point of water:', fahr_to_kelvin(32))\n",
"print('boiling point of water:', fahr_to_kelvin(212))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def this_is_the_function_name(input_argument1, input_argument2):\n",
"\n",
" # The body of the function is indented\n",
" # This function prints the two arguments to screen\n",
" print('The function arguments are:', input_argument1, input_argument2, '(this is done inside the function!)')\n",
"\n",
" # And returns their product\n",
" return input_argument1 * input_argument2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"product_of_inputs = this_is_the_function_name(2,5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(product_of_inputs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"this_is_the_function_name?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every function returns something.\n",
"* return keyword is not compulsory but a function always returns sth\n",
"* A function that doesn’t explicitly <span class=\"label label-default\">return</span> a value automatically returns <span class=\"label label-default\">None</span>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def print_date(year, month, day):\n",
" joined = str(year) + '/' + str(month) + '/' + str(day)\n",
" print(joined)\n",
"\n",
"print_date(1991, 3, 19)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"result = print_date(1991, 3, 19)\n",
"print('result of print_date is:', result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Default values and different order"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Arguments can be given default values with an equal sign in the function declaration. \n",
"* Any arguments in the function without default values is a required argument and MUST come before the argument with default values (which are optional in the function call)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print_date()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print_date(day=1, month=2, year=2003)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def print_date(year=1999, month=9, day=28):\n",
" joined = str(year) + '/' + str(month) + '/' + str(day)\n",
" print(joined)\n",
"\n",
"print_date()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print_date(day=1, month=2, year=2003)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def print_date(year, month=9, day=28):\n",
" joined = str(year) + '/' + str(month) + '/' + str(day)\n",
" print(joined)\n",
"\n",
"print_date(2017)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print_date()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Identifying Syntax Errors</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"1. Read the code below and try to identify what the errors are without running it.<br>\n",
"2. Run the code and read the error message. Is it a SyntaxError or an IndentationError?<br>\n",
"3. Fix the error.<br>\n",
"4. Repeat steps 2 and 3 until you have fixed all the errors.<br>\n",
"def another_function<br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"def another_function\n",
" print(\"Syntax errors are annoying.\")\n",
" print(\"But at least python tells us about them!\")\n",
" print(\"So they are usually not too hard to fix.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Simulating a dynamical system</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"In mathematics, a <a href=\"https://en.wikipedia.org/wiki/Dynamical_system\">dynamical system</a> is a system in which a function describes the time dependence of a point in a geometrical space. Canonical example of a dynamical system is a system called the <a href=\"https://en.wikipedia.org/wiki/Logistic_map\">logistic map</a>.<br><br>\n",
"\n",
"1. Define a function called **logistic_map** that takes two inputs: **X**, representing the state of the system at time t, and a parameter **r**. This function should return a value representing the state of the system at time **t+1**.<br>\n",
"2. Using a for loop, iterate the logistic_map function defined in part 1 starting from an **initial condition** of 0.5 for **T=10**, **100**, and **1000** periods. Store the intermediate results in a list so that after the for loop terminates you have accumulated a sequence of values representing the state of the logistic map at time t=0,1,…,T.<br>\n",
"3. Encapsulate the logic of your for loop into a function called **iterate** that takes the **initial condition** as its first input, the parameter **T** as its second input and the parameter **r** as its third input. The function should return the list of values representing the state of the logistic map at time t=0,1,…,T.<br><br>\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Solucion"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#la posición del sistema en un tiempo dado y de su velocidad\n",
"#posición en función del tiempo\n",
"#ecuación de evolución del sistema dinamico te dice en que punto está el sistema en el tiempo siguiente\n",
"#cada vez se va cercando más al origen pero más despacio\n",
"def logistic_map(X, r):\n",
" return r * X * (1 - X)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"initial_condition = 0.5\n",
"T = 10\n",
"r = 1.0 # r=4, sistema caotico\n",
"trajectory = [initial_condition]\n",
"for t in range(1, T):\n",
" #print(t)\n",
" trajectory.append(logistic_map(trajectory[t-1], r))\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def iterate(initial_condition, T, r):\n",
" trajectory = [initial_condition]\n",
" for t in range(1, T):\n",
" trajectory.append(logistic_map(trajectory[t-1], r))\n",
" \n",
" return trajectory\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"iterate(initial_condition,T,r)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Break programs down into functions to make them easier to understand.</li>\n",
" <li>Functions are reusable</li>\n",
" <li>Define a function using <span class=\"label label-default\">def</span> with a name, parameters, and a block of code.</li>\n",
" <li>Every function returns something.</li>\n",
"<li>Arguments may have default values.</li>\n",
"<li>Any argument without default values is a required argument and MUST come before the argument with default values.</li>\n",
" </ul> \n",
"</div>\n",
"</div>"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conditionals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![jupyter](images/python-flowchart-conditional.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* An <span class=\"label label-default\">if</span> statement (more properly called a <span class=\"label label-default\">conditional</span> statement) controls whether some block of code is executed or not.\n",
"* Structure is similar to a for statement:\n",
" * First line opens with if and ends with a colon\n",
" * Body containing one or more statements is indented (usually by 4 spaces)\n",
"* Use <span class=\"label label-default\">else</span> to execute a block of code when an if condition is not true.\n",
"* Use <span class=\"label label-default\">elif</span> to specify additional tests and provide several alternative choices.\n",
" * Use elif (short for “else if”) and a condition to specify these.\n",
" * Always associated with an if.\n",
" * Must come before the else (which is the “catch all”)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"num = 37\n",
"if num > 100:\n",
" print('greater')\n",
"else:\n",
" print('not greater')\n",
"print('done')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
" a = 0\n",
"\n",
" if a<0: # meets first condition?\n",
"\n",
" # if a IS less than zero\n",
" print('a is a negative number')\n",
"\n",
" elif a>0: # did not meet first condition. meets second condition?\n",
"\n",
" # if a ISN'T less than zero and IS more than zero\n",
" print('a is a positive number')\n",
"\n",
" else: # met neither condition\n",
"\n",
" # if a ISN'T less than zero and ISN'T more than zero\n",
" print('a must be zero!')"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# Conditionals are often used inside loops.\n",
"* Conditions are tested once, in order, that's why they are ften used inside loops.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"numbers = [2, -1, 0, 10,-15,20,30]\n",
"for n in numbers:\n",
" if n<0: # meets first condition?\n",
"\n",
" # if a IS less than zero\n",
" print(n, 'is a negative number')\n",
"\n",
" elif n>0: # did not meet first condition. meets second condition?\n",
"\n",
" # if a ISN'T less than zero and IS more than zero\n",
" print(n, ' is a positive number')\n",
"\n",
" else: # met neither condition\n",
"\n",
" # if a ISN'T less than zero and ISN'T more than zero\n",
" print(n, ' must be zero!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Combining conditions: using <span class=\"label label-default\">and</span>, <span class=\"label label-default\">or</span> and parenthesis"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Imaging that you need to meet two conditions\n",
"if (1 > 0) and (-1 > 0):\n",
" print('both parts are true')\n",
"else:\n",
" print('at least one part is false')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 > 0) and (0 == 0):\n",
" print('both parts are true')\n",
"else:\n",
" print('at least one part is false')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 < 0) or (-1 < 0):\n",
" print('at least one test is true')\n",
"else:\n",
" print('both parts are false')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 < 0) or (10 < 0):\n",
" print('at least one test is true')\n",
"else:\n",
" print('both parts are false')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - What Is Truth?</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"<span class=\"label label-default\">True</span> and <span class=\"label label-default\">False</span> are special words in Python called <span class=\"label label-default\">booleans</span> which represent true and false statements. However, they aren’t the only values in Python that are true and false. In fact, any value can be used in an if or elif. After reading and running the code below, explain what the rule is for which values are considered true and which are considered false.<br>\n",
"\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "raw",
"metadata": {
"scrolled": true
},
"source": [
"if '':\n",
" print('empty string is true')\n",
"if 'word':\n",
" print('word is true')\n",
"if []:\n",
" print('empty list is true')\n",
"if [1, 2, 3]:\n",
" print('non-empty list is true')\n",
"if 0:\n",
" print('zero is true')\n",
"if 1:\n",
" print('one is true')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Counting Vowels</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"1. Write a loop that counts the number of vowels in a character string.<br>\n",
"2. Test it on a few individual words and full sentences.<br>\n",
"3. Once you are done, compare your solution to your neighbor’s. <br>\n",
"\n",
" </div>\n",
"</div>\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Solution\n",
"vowels = 'aeiouAEIOU'\n",
"sentence = 'We are going to count the number of vowels.'\n",
"count = 0\n",
"for char in sentence:\n",
" if char in vowels:\n",
" count += 1\n",
" \n",
"print(\"The number of vowels in this string is \" + str(count))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Use <span class=\"label label-default\">if</span> condition to start a conditional statement, <span class=\"label label-default\">elif</span> condition to provide additional tests, and <span class=\"label label-default\">else</span> to provide a default.</li>\n",
" <li>The bodies of the branches of conditional statements must be indented.</li>\n",
" <li>Conditionals are often used inside loops.</li>\n",
" <li>Use <span class=\"label label-default\">==</span> to test for equality.</li>\n",
" <li>X and Y is only true if both X and Y are true.</li>\n",
" <li>X or Y is true if either X or Y, or both, are true.</li>\n",
" <li>Zero, the empty string, and the empty list are considered false; all other numbers, strings, and lists are considered true.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment