Skip to content

Instantly share code, notes, and snippets.

@jhamrick
Created July 23, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhamrick/644705548088283434a3 to your computer and use it in GitHub Desktop.
Save jhamrick/644705548088283434a3 to your computer and use it in GitHub Desktop.
Introduction to the IPython Notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"In this class, you will be using the IPython Notebook to write code and written responses to assignments. "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"The notebook consists of a series of *cells*. For example, this text is in what is called a \"Markdown cell\". The following cell is a \"code cell\":"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"# this is a code cell"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"You can tell what the type of a cell is by selecting the cell, and looking at the toolbar at the top of the page. For example, try clicking on this cell. You should see the cell type menu displaying \"Markdown\", like this:\n",
"\n",
"![](images/cell-type-menu.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"## Command mode and edit mode"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"In the notebook, there are two modes: *edit mode* and *command mode*. By default the notebook begins in *command mode*. In order to edit a cell, you need to be in *edit mode*."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-info\">\n",
"<b>When you are in command mode</b>, you can press <b>enter</b> to switch to edit mode. The outline of the cell you currently have selected will turn green, and a cursor will appear.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-info\">\n",
"<b>When you are in edit mode</b>, you can press <b>escape</b> to switch to command mode. The outline of the cell you currently have selected will turn gray, and the cursor will disappear.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"### Markdown cells\n",
"\n",
"For example, a markdown cell might look like this in **command mode** (Note: the following few cells are not actually cells -- they are images and just look like cells! This is for demonstration purposes only.)\n",
"\n",
"![](images/command-mode-markdown-rendered.png)\n",
"\n",
"Then, when you press enter, it will change to **edit mode**:\n",
"\n",
"![](images/edit-mode-markdown.png)\n",
"\n",
"Now, when we press escape, it will change back to **command mode**:\n",
"\n",
"![](images/command-mode-markdown-unrendered.png)\n",
"\n",
"However, you'll notice that the cell no longer looks like it did originally. This is because IPython will only *render* the markdown when you tell it to. To do this, we need to \"run\" the cell by pressing **`Ctrl-Enter`**, and then it will go back to looking like it did originally:\n",
"\n",
"![](images/command-mode-markdown-rendered.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"### Code cells\n",
"\n",
"For code cells, it is pretty much the same thing. This is what a code cell looks like in command mode (again, the next few cells LOOK like cells, but are just images):\n",
"\n",
"![](images/command-mode-outline.png)\n",
"\n",
"If we press enter, it will change to **edit mode**:\n",
"\n",
"![](images/edit-mode-outline.png)\n",
"\n",
"And pressing escape will also go back to **command mode**:\n",
"\n",
"![](images/command-mode-outline.png)\n",
"\n",
"If we were to press **`Ctrl-Enter`** like we did for the markdown cell, this would actually *run* the code in the code cell:\n",
"\n",
"![](images/code-cell-run.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"## Executing cells"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"Code cells can contain any valid Python code in them. When you run the cell, the code is executed and any output is displayed."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-info\">\n",
"You can execute cells with <b><code>Ctrl-Enter</code></b> (which will keep the cell selected), or <b><code>Shift-Enter</code></b> (which will select the next cell).\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"Try running the following cell and see what it prints out:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"print(\"Printing cumulative sum from 1-10:\")\n",
"total = 0\n",
"for i in range(1, 11):\n",
" total += i\n",
" print(\"Sum of 1 to \" + str(i) + \" is: \" + str(total))\n",
"print(\"Done printing numbers.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"You'll notice that the output beneath the cell corresponds to the `print` statements in the code. Here is another example, which only prints out the final sum:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"total = 0\n",
"for i in range(1, 11):\n",
" total += i\n",
"print(total)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"Another way to print something out is to have that thing be the last line in the cell. For example, we could rewrite our example above to be:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"total = 0\n",
"for i in range(1, 11):\n",
" total += i\n",
"total"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"However, this *will not work* unless the thing to be displayed is on the last line. For example, if we wanted to print the total sum and then a message after that, this will not do what we want (it will only print \"Done computing total.\", and not the total sum itself)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"total = 0\n",
"for i in range(1, 11):\n",
" total += i\n",
"total\n",
"print(\"Done computing total.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you are accustomed to Python 2, note that the parentheses are obligatory for the `print` function in Python 3."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"## The IPython kernel"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"When you first start a notebook, you are also starting what is called a *kernel*. This is a special program that runs in the background and executes Python code. Whenever you run a code cell, you are telling the kernel to execute the code that is in the cell, and to print the output (if any).\n",
"\n",
"Just like if you were typing code at the Python interpreter, you need to make sure your variables are declared before you can use them. What will happen when you run the following cell? Try it and see:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"a"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"The issue is that the variable `a` does not exist. Modify the cell above so that `a` is declared first (for example, you could set the value of `a` to 1 -- or pick whatever value you want). Once you have modified the above cell, you should be able to run the following cell (if you haven't modified the above cell, you'll get the same error!):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(\"The value of 'a' is: \" + str(a))"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"Running the above cell should work, because `a` has now been declared. To see what variables have been declared, you can use the `%whos` command:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"If you ran the summing examples from the previous section, you'll notice that `total` and `i` are listed under the `%whos` command. That is because when we ran the code for those examples, they also modified the kernel state."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"(Note that commands beginning with a percent (%) or double percent (%%) are special IPython commands called *magics*. They will **only** work in IPython.)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"### Restarting the kernel"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"It is generally a good idea to periodically restart the kernel and start fresh, because you may be using some variables that you declared at some point, but at a later point deleted that declaration. "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-danger\">\n",
"Your code should <b>always</b> be able to work if you run every cell in the notebook, in order, starting from a new kernel. </div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"To test that your code can do this, first restart the kernel by clicking the restart button:\n",
"\n",
"![](images/restart-kernel-button.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"Then, run all cells in the notebook in order by choosing **Cell$\\rightarrow$Run All** from the menu above."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-info\">\n",
"There are many keyboard shortcuts for the notebook. To see a full list of these, go to <b>Help$\\rightarrow$Keyboard Shortcuts</b>.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-info\">To learn a little more about what things are what in the IPython Notebook, check out the user interface tour, which you can access by going to <b>Help$\\rightarrow$User Interface Tour</b>.</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"## Tests"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"For many of the coding assignments we give you, we will provide tests that your code must pass. These will be in one or more cells after the code you need to write, and they *must* pass for you to get credit. In the following exercise, there is one test cell after the cell where you should put your answer. "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {}
},
"source": [
"<div class=\"alert alert-success\">\n",
"Implement the function <code>hello</code> and make sure the test cells runs without any errors. You will need to delete the line with `raise NotImplementedError`, write your own solution, and then re-run the cell before running the test cell. Each time you change code in a cell, you will need to re-run that cell before running any other cells that depend on it!\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {
"grade_id": "hello",
"solution": true
}
},
"outputs": [],
"source": [
"def hello(name):\n",
" \"\"\"Returns a message containing \"Hello, <name>!\", \n",
" where <name> is passed in as an argument.\n",
" \n",
" Parameters\n",
" ----------\n",
" name : string\n",
" The name of the person to say hello to\n",
" \n",
" Returns\n",
" -------\n",
" the message containing \"Hello, <name>!\"\n",
" \n",
" \"\"\"\n",
" ### BEGIN SOLUTION\n",
" return \"Hello, \" + name + \"!\"\n",
" ### END SOLUTION"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {}
},
"outputs": [],
"source": [
"# try running your hello function with your own name and see what \n",
"# it returns\n",
"hello(\"YOUR NAME HERE\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Hint: if the test cell is not passing, but your function seems\n",
"# to be showing the right thing, make sure you are actually \n",
"# returning a value from your function! You should be using \n",
"# `return`, not `print`. For example, this cell should display:\n",
"#\n",
"# Your function returned: Hello, Reverend Bayes!\n",
"# \n",
"# and not:\n",
"#\n",
"# Hello, Reverend Bayes!\n",
"# Your function returned: None\n",
"\n",
"message = hello(\"Reverend Bayes\")\n",
"print(\"Your function returned: \" + str(message))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# add your own test cases in this cell!\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"nbgrader": {
"grade": true,
"grade_id": "test_hello",
"points": "1"
}
},
"outputs": [],
"source": [
"\"\"\"(1 point) Test code for the 'hello' function. This cell should NOT give any errors when it is run.\"\"\"\n",
"from nose.tools import assert_equal\n",
"assert_equal(hello(\"Jessica\"), \"Hello, Jessica!\")\n",
"assert_equal(hello(\"jessica\"), \"Hello, jessica!\")\n",
"assert_equal(hello(\"Tom\"), \"Hello, Tom!\")\n",
"assert_equal(hello(\"123\"), \"Hello, 123!\")\n",
"\n",
"print(\"Success!\")"
]
}
],
"metadata": {
"celltoolbar": "Create Assignment",
"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.4.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment