{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1.1. Introducing the IPython notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. We assume that you have installed a Python distribution with IPython, and that you are now in an IPython notebook. Type in a cell the following command, and press `Shift+Enter` to validate it:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"Hello world!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A notebook contains a linear succession of **cells** and **output areas**. A cell contains Python code, in one or multiple lines. The output of the code is shown in the corresponding output area." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2. Now, we do a simple arithmetic operation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "2+2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result of the operation is shown in the output area. Let's be more precise. The output area not only displays text that is printed by any command in the cell, it also displays a text representation of the last returned object. Here, the last returned object is the result of `2+2`, i.e. `4`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3. In the next cell, we can recover the value of the last returned object with the `_` (underscore) special variable. In practice, it may be more convenient to assign objects to named variables, like in `myresult = 2+2`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "_ * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4. IPython not only accepts Python code, but also shell commands. Those are defined by the operating system (Windows, Linux, Mac OS X, etc.). We first type `!` in a cell before typing the shell command. Here, we get the list of notebooks in the current directory." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "!ls *.ipynb" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "5. IPython comes with a library of **magic commands**. Those commands are convenient shortcuts to common actions. They all start with `%` (percent character). You can get the list of all magic commands with `%lsmagic`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%lsmagic" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cell magic have a `%%` prefix: they apply to an entire cell in the notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "6. For example, the `%%writefile` cell magic lets you create a text file easily. This magic command accepts a filename as argument. All remaining lines in the cell are directly written to this text file. Here, we create a file `test.txt` and we write `Hello world!` in it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%%writefile test.txt\n", "Hello world!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Let's check what this file contains.\n", "with open('test.txt', 'r') as f:\n", " print(f.read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "7. As you can see in the output of `%lsmagic`, there are many magic commands in IPython. You can find more information about any command by adding a `?` after it. For example, here is how we get help about the `%run` magic command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "style": "hidden" }, "outputs": [], "source": [ "# You can omit this, it is just to force help output\n", "# to print in the standard output, rather than \n", "# in the pager. This might change in future versions\n", "# of IPython.\n", "from __future__ import print_function\n", "from IPython.core import page\n", "page.page = print" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "strip_output": [ 10, 10 ] }, "outputs": [], "source": [ "%run?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "8. We covered the basics of IPython and the notebook. Let's now turn to the rich display and interactive features of the notebook. Until now, we only created **code cells**, i.e. cells that contain... code. There are other types of cells, notably **Markdown cells**. Those contain rich text formatted with **Markdown**, a popular plain text formatting syntax. This format supports normal text, headers, bold, italics, hypertext links, images, mathematical equations in LaTeX, code, HTML elements, and other features, as shown below." ] }, { "cell_type": "raw", "metadata": {}, "source": [ "### New paragraph\n", "\n", "This is *rich* **text** with [links](http://ipython.org), equations:\n", "\n", "$$\\hat{f}(\\xi) = \\int_{-\\infty}^{+\\infty} f(x)\\, \\mathrm{e}^{-i \\xi x}$$\n", "\n", "code with syntax highlighting:\n", "\n", "```python\n", "print(\"Hello world!\")\n", "```\n", "\n", "and images:\n", "\n", "![This is an image](http://ipython.org/_static/IPy_header.png)" ] }, { "cell_type": "markdown", "metadata": { "style": "hidden" }, "source": [ "### New paragraph\n", "\n", "This is *rich* **text** with [links](http://ipython.org), equations:\n", "\n", "$$\\hat{f}(\\xi) = \\int_{-\\infty}^{+\\infty} f(x)\\, \\mathrm{e}^{-i \\xi x}$$\n", "\n", "code with syntax highlighting:\n", "\n", "```python\n", "print(\"Hello world!\")\n", "```\n", "\n", "and images:\n", "\n", "![This is an image](http://ipython.org/_static/IPy_header.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By combining code cells and Markdown cells, you can create a standalone interactive document that combines computations (code), text and graphics." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "9. That was it for Markdown cells. IPython also comes with a sophisticated display system that lets you insert rich web elements in the notebook. Here, we show how to add HTML, SVG (Scalable Vector Graphics) and even Youtube videos in a notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First, we need to import some classes." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from IPython.display import HTML, SVG, YouTubeVideo" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We create an HTML table dynamically with Python, and we display it in the (HTML-based) notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "HTML('''\n", "\n", "''' + \n", "''.join(['' + \n", " ''.join([''.format(\n", " row=row, col=col\n", " ) for col in range(5)]) +\n", " '' for row in range(5)]) +\n", "'''\n", "
{row},{col}
\n", "''')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly here, we create a SVG graphics dynamically." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "SVG('''''' + \n", "''.join(['''\n", " '''.format(\n", " x=(30+3*i)*(10-i), y=30, r=3.*float(i)\n", " ) for i in range(10)]) + \n", "'''''')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we display a Youtube video by giving its identifier to `YoutubeVideo`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "YouTubeVideo('j9YpkSX7NNM')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "10. Now, we illustrate the latest interactive features in IPython 2.0+. This version brings graphical widgets in the notebook that can interact with Python objects. We will create a drop-down menu allowing us to display one among several videos." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from collections import OrderedDict\n", "from IPython.display import display, clear_output\n", "from ipywidgets import Dropdown\n", "#from IPython.html.widgets import DropdownWidget # IPython < 4.x" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# We create a Dropdown widget, with a dictionary containing\n", "# the keys (video name) and the values (Youtube identifier) \n", "# of every menu item.\n", "dw = Dropdown(options=OrderedDict([\n", "# dw = DropdownWidget(values=OrderedDict([ # IPython < 4.x\n", " ('SciPy 2012', 'iwVvqwLDsJo'), \n", " ('PyCon 2012', '2G5YTlheCbw'),\n", " ('SciPy 2013', 'j9YpkSX7NNM')]))\n", "# We create a callback function that displays the requested\n", "# Youtube video.\n", "def on_value_change(name, val):\n", " clear_output()\n", " display(YouTubeVideo(val))\n", "# Every time the user selects an item, the function\n", "# `on_value_change` is called, and the `val` argument\n", "# contains the value of the selected item.\n", "dw.on_trait_change(on_value_change, 'value')\n", "# We choose a default value.\n", "dw.value = dw.options['SciPy 2013']\n", "# dw.value = dw.values['SciPy 2013'] # IPyhon < 4.x\n", "# Finally, we display the widget.\n", "display(dw)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The interactive features of IPython 2.0 bring a whole new dimension in the notebook, and we can expect many developments in the months and years to come." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).\n", "\n", "> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages)." ] } ], "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.0" } }, "nbformat": 4, "nbformat_minor": 0 }