Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning IPython for Interactive Computing and Data Visualization, Second Edition
Learning IPython for Interactive Computing and Data Visualization, Second Edition

Learning IPython for Interactive Computing and Data Visualization, Second Edition: Get started with Python for data analysis and numerical computing in the Jupyter notebook

Arrow left icon
Profile Icon Cyrille Rossant
Arrow right icon
₱2296.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (12 Ratings)
Paperback Oct 2015 200 pages 1st Edition
eBook
₱579.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial
Arrow left icon
Profile Icon Cyrille Rossant
Arrow right icon
₱2296.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (12 Ratings)
Paperback Oct 2015 200 pages 1st Edition
eBook
₱579.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial
eBook
₱579.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning IPython for Interactive Computing and Data Visualization, Second Edition

Chapter 1. Getting Started with IPython

In this chapter, we will cover the following topics:

  • What are Python, IPython, and Jupyter?
  • Installing Python with Anaconda
  • Introducing the Notebook
  • A crash course on Python
  • Ten Jupyter/IPython essentials

What are Python, IPython, and Jupyter?

Python is an open source general-purpose language created by Guido van Rossum in the late 1980s. It is widely-used by system administrators and developers for many purposes: for example, automating routine tasks or creating a web server. Python is a flexible and powerful language, yet it is sufficiently simple to be taught to school children with great success.

In the past few years, Python has also emerged as one of the leading open platforms for data science and high-performance numerical computing. This might seem surprising as Python was not originally designed for scientific computing. Python's interpreted nature makes it much slower than lower-level languages like C or Fortran, which are more amenable to number crunching and the efficient implementation of complex mathematical algorithms.

However, the performance of these low-level languages comes at a cost: they are hard to use and they require advanced knowledge of how computers work. In the late 1990s, several scientists began investigating the possibility of using Python for numerical computing by interoperating it with mainstream C/Fortran scientific libraries. This would bring together the ease-of-use of Python with the performance of C/Fortran: the dream of any scientist!

Consequently, the past 15 years have seen the development of widely-used libraries such as NumPy (providing a practical array data structure), SciPy (scientific computing), matplotlib (graphical plotting), pandas (data analysis and statistics), scikit-learn (machine learning), SymPy (symbolic computing), and Jupyter/IPython (efficient interfaces for interactive computing). Python, along with this set of libraries, is sometimes referred to as the SciPy stack or PyData platform.

Tip

Competing platforms

Python has several competitors. For example, MATLAB (by Mathworks) is a commercial software focusing on numerical computing that is widely-used in scientific research and engineering. SPSS (by IBM) is a commercial software for statistical analysis. Python, however, is free and open source, and that's one of its greatest strengths. Alternative open source platforms include R (specialized in statistics) and Julia (a young language for high-performance numerical computing).

More recently, this platform has gained popularity in other non-academic communities such as finance, engineering, statistics, data science, and others.

This book provides a solid introduction to the whole platform by focusing on one of its main components: Jupyter/IPython.

Jupyter and IPython

IPython was created in 2001 by Fernando Perez (the I in IPython stands for "interactive"). It was originally meant to be a convenient command-line interface to the scientific Python platform. In scientific computing, trial and error is the rule rather than the exception, and this requires an efficient interface that allows for interactive exploration of algorithms, data, and graphs.

In 2011, IPython introduced the interactive Notebook. Inspired by commercial software such as Maple (by Maplesoft) or Mathematica (by Wolfram Research), the Notebook runs in a browser and provides a unified web interface where code, text, mathematical equations, plots, graphics, and interactive graphical controls can be combined into a single document. This is an ideal interface for scientific computing. Here is a screenshot of a notebook:

Jupyter and IPython

Example of a notebook

It quickly became clear that this interface could be used with languages other than Python such as R, Julia, Lua, Ruby, and many others. Further, the Notebook is not restricted to scientific computing: it can be used for academic courses, software documentation, or book writing thanks to conversion tools targeting Markdown, HTML, PDF, ODT, and many other formats. Therefore, the IPython developers decided in 2014 to acknowledge the general-purpose nature of the Notebook by giving a new name to the project: Jupyter.

Jupyter features a language-independent Notebook platform that can work with a variety of kernels. Implemented in any language, a kernel is the backend of the Notebook interface. It manages the interactive session, the variables, the data, and so on. By contrast, the Notebook interface is the frontend of the system. It manages the user interface, the text editor, the plots, and so on. IPython is henceforth the name of the Python kernel for the Jupyter Notebook. Other kernels include IR, IJulia, ILua, IRuby, and many others (50 at the time of this writing).

In August 2015, the IPython/Jupyter developers achieved the "Big Split" by splitting the previous monolithic IPython codebase into a set of smaller projects, including the language-independent Jupyter Notebook (see https://blog.jupyter.org/2015/08/12/first-release-of-jupyter/). For example, the parallel computing features of IPython are now implemented in a standalone Python package named ipyparallel, the IPython widgets are implemented in ipywidgets, and so on. This separation makes the code of the project more modular and facilitates third-party contributions. IPython itself is now a much smaller project than before since it only features the interactive Python terminal and the Python kernel for the Jupyter Notebook.

Note

You will find the list of changes in IPython 4.0 at http://ipython.readthedocs.org/en/latest/whatsnew/version4.html. Many internal IPython imports have been deprecated due to the code reorganization. Warnings are raised if you attempt to perform a deprecated import. Also, the profiles have been removed and replaced with a unique default profile. However, you can simulate this functionality with environment variables. You will find more information at http://jupyter.readthedocs.org.

What this book covers

This book covers the Jupyter Notebook 1.0 and focuses on its Python kernel, IPython 4.0. In this chapter, we will introduce the platform, the Python language, the Jupyter Notebook interface, and IPython. In the remaining chapters, we will cover data analysis and scientific computing in Jupyter/IPython with the help of mainstream scientific libraries such as NumPy, pandas, and matplotlib.

Note

This book gives you a solid introduction to Jupyter and the SciPy platform. The IPython Interactive Computing and Visualization Cookbook (http://ipython-books.github.io/cookbook/) is the sequel of this introductory-level book. In 15 chapters and more than 500 pages, it contains a hundred recipes covering a wide range of interactive numerical computing techniques and data science topics. The IPython Cookbook is an excellent addition to the present IPython minibook if you're interested in delving into the platform in much greater detail.

References

Here are a few references about IPython and the Notebook:

Installing Python with Anaconda

Although Python is an open-source, cross-platform language, installing it with the usual scientific packages used to be overly complicated. Fortunately, there is now an all-in-one scientific Python distribution, Anaconda (by Continuum Analytics), that is free, cross-platform, and easy to install. Anaconda comes with Jupyter and all of the scientific packages we will use in this book. There are other distributions and installation options (like Canopy, WinPython, Python(x, y), and others), but for the purpose of this book we will use Anaconda throughout.

Tip

Running Jupyter in the cloud

You can also use Jupyter directly from your web browser, without installing anything on your local computer: go to http://try.jupyter.org. Note that the notebooks created there are not saved. Let's also mention a similar service, Wakari (https://wakari.io), by Continuum Analytics.

Anaconda comes with a package manager named conda, which lets you manage your Python distribution and install new packages.

Tip

Miniconda

Miniconda (http://conda.pydata.org/miniconda.html) is a light version of Anaconda that gives you the ability to only install the packages you need.

Downloading Anaconda

The first step is to download Anaconda from Continuum Analytics' website (http://continuum.io/downloads). This is actually not the easiest part since several versions are available. Three properties define a particular version:

  • The operating system (OS): Linux, Mac OS X, or Windows. This will depend on the computer you want to install Python on.
  • 32-bit or 64-bit: You want the 64-bit version, unless you're on an old or low-end computer. The 64-bit version will allow you to manipulate large datasets.
  • The version of Python: 2.7, or 3.4 (or later). In this book, we will use Python 3.4. You can also use Python 3.5 (released in September 2015) which introduces many features, including a new @ operator for matrix multiplication. However, it is easy to temporarily switch to a Python 2.7 environment with Anaconda if necessary (see the next section).

    Note

    Python 3 brought a few backward-incompatible changes over Python 2 (also known as Legacy Python). This is why many people are still using Python 2.7 at this time, even though Python 3 was released in 2008. We will use Python 3 in this book, and we recommend that newcomers learn Python 3. If you need to use legacy Python code that hasn't yet been updated to Python 3, you can use conda to temporarily switch to a Python 2 interpreter.

Once you have found the right link for your OS and Python 3 64-bit, you can download the package. You should then find it in your downloads directory (depending on your OS and your browser's settings).

Installing Anaconda

The Anaconda installer comes in different flavors depending on your OS, as follows:

  • Linux: The Linux installer is a bash .sh script. Run it with a command like bash Anaconda3-2.3.0-Linux-x86_64.sh (if necessary, replace the filename by the one you downloaded).
  • Mac: The Mac graphical installer is a .pkg file that you can run with a double-click.
  • Windows: The Windows graphical installer is an .exe file that you can run with a double-click.

Then, follow the instructions to install Anaconda on your computer. Here are a few remarks:

  • You don't need administrator rights to install Anaconda. In most cases, you can choose to install it in your personal user account.
  • Choose to put Anaconda in your system path, so that Anaconda's Python is the system default.

Note

Anaconda comes with a graphical launcher that you can use to start IPython, manage environments, and so on. You will find more details at http://docs.continuum.io/anaconda-launcher/

Before you get started...

Before you get started with Anaconda, there are a few things you need to know:

  • Opening a terminal
  • Finding your home directory
  • Manipulating your system path

You can skip this section if you already know how to do these things.

Opening a terminal

A terminal is a command-line application that lets you interact with your computer by typing commands with the keyboard, instead of clicking on windows with the mouse. While most computer users only know Graphical User Interfaces, developers and scientists generally need to know how to use the command-line interface for advanced usage. To use the command-line interface, follow the instructions that are specific to your OS:

  • On Windows, you can use Powershell. Press the Windows + R keys, type powershell in the Run box, and press Enter. You will find more information about Powershell at https://blog.udemy.com/powershell-tutorial/. Alternatively, you can use the older Windows terminal by typing cmd in the Run box.
  • On OS X, you can open the Terminal application, for example by pressing Cmd + Space, typing terminal, and pressing Enter.
  • On Linux, you can open the Terminal from your application manager.

In a terminal, use the cd /path/to/directory command to move to a given directory. For example, cd ~ moves to your home directory, which is introduced in the next section.

Finding your home directory

Your home directory is specific to your user account on your computer. It generally contains your applications' settings. It is often referred to as ~.Depending on the OS, the location of the home directory is as follows:

  • On Windows, its location is C:\Users\YourName\ where YourName is the name of your account.
  • On OS X, its location is /Users/YourName/ where YourName is the name of your account.
  • On Linux, its location is generally /home/yourname/ where yourname is the name of your account.

For example, the directory ~/anaconda3 refers to C:\Users\YourName\anaconda3\ on Windows and /home/yourname/anaconda3/ on Linux.

Manipulating your system path

The system path is a global variable (also called an environment variable) defined by your operating system with the list of directories where executable programs are located. If you type a command like python in your terminal, you generally need to have a python (or python.exe on Windows) executable in one of the directories listed in the system path. If that's not the case, an error may be raised.

You can manually add directories to your system path as follows:

  • On Windows, press the Windows + R keys, type rundll32.exe sysdm.cpl,EditEnvironmentVariables, and press Enter. You can then edit the PATH variable and append ;C:\path\to\directory if you want to add that directory. You will find more detailed instructions at http://www.computerhope.com/issues/ch000549.htm.
  • On OS X, edit or create the file ~/.bash_profile and add export PATH="$PATH:/path/to/directory" at the end of the file.
  • On Linux, edit or create the file ~/.bashrc and add export PATH="$PATH:/path/to/directory" at the end of the file.

Testing your installation

To test Anaconda once it has been installed, open a terminal and type python. This opens a Python console, not to be confused with the OS terminal. The Python console is identified with a >>> prompt string, whereas the OS terminal is identified with a $ (Linux/OS X) or > (Windows) prompt string. These strings are displayed in the terminal, often preceded by your computer's name, your login, and the current directory (for example, yourname@computer:~$ on Linux or PS C:\Users\YourName> on Windows). You can type commands after the prompt string. After typing python, you should see something like the following:

$ python
Python 3.4.3 |Anaconda 2.3.0 (64-bit)| (default, Jun  4 2015, 15:29:08) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

What matters is that Anaconda or Continuum Analytics is mentioned here. Otherwise, typing python might have launched your system's default Python, which is not the one you want to use in this book.

If you have this problem, you may need to add the path to the Anaconda executables to your system path. For example, this path will be ~/anaconda3/bin if you chose to install Anaconda in ~/anaconda3. The bin directory contains Anaconda executables including python.

If you have any problem installing and testing Anaconda, you can ask for help on the mailing list (see the link in the References section under the Installing Python with Anaconda section of this chapter).

Next, exit the Python prompt by typing exit() and pressing Enter.

Managing environments

Anaconda lets you create different isolated Python environments. For example, you can have a Python 2 distribution for the rare cases where you need to temporarily switch to Python 2.

To create a new environment for Python 2, type the following command in an OS terminal:

$ conda create -n py2 anaconda python=2.7

This will create a new isolated environment named py2 based on the original Anaconda distribution, but with Python 2.7. You could also use the command conda env: type conda env -h to see the details.

You can now activate your py2 environment by typing the following command in a terminal:

Now, you should see a (py2) prefix in front of your terminal prompt. Typing python in your terminal with the py2 environment activated will open a Python 2 interpreter.

Type deactivate on Windows or source deactivate on Linux/OS X to deactivate the environment in the terminal.

Common conda commands

Here is a list of common commands:

  • conda help: Displays the list of conda commands.
  • conda list: Lists all packages installed in the current environment.
  • conda info: Displays system information.
  • conda env list: Displays the list of environments installed. The currently active one is marked by a star *.
  • conda install somepackage: Installs a Python package (replace somepackage by the name of the package you want to install).
  • conda install somepackage=0.7: Installs a specific version of a package.
  • conda update somepackage: Updates a Python package to the latest available version.
  • conda update anaconda: Updates all packages.
  • conda update conda: Updates conda itself.
  • conda update --all: Updates all packages.
  • conda remove somepackage: Uninstalls a Python package.
  • conda remove -n myenv --all: Removes the environment named myenv (replace this by the name of the environment you want to uninstall).
  • conda clean -t: Removes the old tarballs that are left over after installation and updates.

Some commands ask for confirmation (you need to press y to confirm). You can also use the -y option to avoid the confirmation prompt.

If conda install somepackage fails, you can try pip install somepackage instead. This will use the Python Package Index (PyPI) instead of Anaconda. Many scientific Anaconda packages are easier to install than the corresponding PyPI packages because they are precompiled for your platform. However, many packages are available on PyPI but not on Anaconda.

Here are some references:

References

Here are a few references about Anaconda:

Downloading the notebooks

All of this book's code is available on GitHub as notebooks. We recommend that you download the notebooks and experiment with them as you're working through the book.

Note

GitHub is a popular online service that hosts open source projects. It is based on the Git Distributed Version Control System (DVCS). Git keeps track of file changes and enables collaborative work on a given project. Learning a version control system like Git is highly recommended for all programmers. Not using a version control system when working with code or even text documents is now considered as bad practice. You will find several references at https://help.github.com/articles/good-resources-for-learning-git-and-github/. The IPython Cookbook also contains several recipes about Git and best interactive programming practices.

Here is how to download the book's notebooks:

  • Install git: http://git-scm.com/downloads.
  • Check your git installation: Open a new OS terminal and type git version. You should see the version of git and not an error message.
  • Type the following command (this is a single line):
    $ git clone https://github.com/ipython-books/minibook-2nd-code.git  "$HOME/minibook"
    

This will download the very latest version of the code into a minibook subdirectory in your home directory. You can also choose another directory.

From this directory, you can update to the latest version at any time by typing git pull.

Tip

Notebooks on GitHub

Notebook documents stored on GitHub (with the file extension .ipynb) are automatically rendered on the GitHub website.

Introducing the Notebook

Originally, IPython provided an enhanced command-line console to run Python code interactively. The Jupyter Notebook is a more recent and more sophisticated alternative to the console. Today, both tools are available, and we recommend that you learn to use both.

Launching the IPython console

To run the IPython console, type ipython in an OS terminal. There, you can write Python commands and see the results instantly. Here is a screenshot:

Launching the IPython console

IPython console

The IPython console is most convenient when you have a command-line-based workflow and you want to execute some quick Python commands.

You can exit the IPython console by typing exit.

Note

Let's mention the Qt console, which is similar to the IPython console but offers additional features such as multiline editing, enhanced tab completion, image support, and so on. The Qt console can also be integrated within a graphical application written with Python and Qt. See http://jupyter.org/qtconsole/stable/ for more information.

Launching the Jupyter Notebook

To run the Jupyter Notebook, open an OS terminal, go to ~/minibook/ (or into the directory where you've downloaded the book's notebooks), and type jupyter notebook. This will start the Jupyter server and open a new window in your browser (if that's not the case, go to the following URL: http://localhost:8888). Here is a screenshot of Jupyter's entry point, the Notebook dashboard:

Launching the Jupyter Notebook

The Notebook dashboard

Note

At the time of writing, the following browsers are officially supported: Chrome 13 and greater; Safari 5 and greater; and Firefox 6 or greater. Other browsers may work also. Your mileage may vary.

The Notebook is most convenient when you start a complex analysis project that will involve a substantial amount of interactive experimentation with your code. Other common use-cases include keeping track of your interactive session (like a lab notebook), or writing technical documents that involve code, equations, and figures.

In the rest of this section, we will focus on the Notebook interface.

Tip

Closing the Notebook server

To close the Notebook server, go to the OS terminal where you launched the server from, and press Ctrl + C. You may need to confirm with y.

The Notebook dashboard

The dashboard contains several tabs:

  • Files: shows all files and notebooks in the current directory
  • Running: shows all kernels currently running on your computer
  • Clusters: lets you launch kernels for parallel computing (covered in Chapter 5, High-Performance and Parallel Computing)

A notebook is an interactive document containing code, text, and other elements. A notebook is saved in a file with the .ipynb extension. This file is a plain text file storing a JSON data structure.

A kernel is a process running an interactive session. When using IPython, this kernel is a Python process. There are kernels in many languages other than Python.

Note

We follow the convention to use the term notebook for a file, and Notebook for the application and the web interface.

In Jupyter, notebooks and kernels are strongly separated. A notebook is a file, whereas a kernel is a process. The kernel receives snippets of code from the Notebook interface, executes them, and sends the outputs and possible errors back to the Notebook interface. Thus, in general, the kernel has no notion of a Notebook. A notebook is persistent (it's a file), whereas a kernel may be closed at the end of an interactive session and it is therefore not persistent. When a notebook is re-opened, it needs to be re-executed.

In general, no more than one Notebook interface can be connected to a given kernel. However, several IPython consoles can be connected to a given kernel.

The Notebook user interface

To create a new notebook, click on the New button, and select Notebook (Python 3). A new browser tab opens and shows the Notebook interface as follows:

The Notebook user interface

A new notebook

Here are the main components of the interface, from top to bottom:

  • The notebook name, which you can change by clicking on it. This is also the name of the .ipynb file.
  • The Menu bar gives you access to several actions pertaining to either the notebook or the kernel.
  • To the right of the menu bar is the Kernel name. You can change the kernel language of your notebook from the Kernel menu. We will see in Chapter 6, Customizing IPython how to manage different kernel languages.
  • The Toolbar contains icons for common actions. In particular, the dropdown menu showing Code lets you change the type of a cell.
  • Following is the main component of the UI: the actual Notebook. It consists of a linear list of cells. We will detail the structure of a cell in the following sections.

Structure of a notebook cell

There are two main types of cells: Markdown cells and code cells, and they are described as follows:

  • A Markdown cell contains rich text. In addition to classic formatting options like bold or italics, we can add links, images, HTML elements, LaTeX mathematical equations, and more. We will cover Markdown in more detail in the Ten Jupyter/IPython essentials section of this chapter.
  • A code cell contains code to be executed by the kernel. The programming language corresponds to the kernel's language. We will only use Python in this book, but you can use many other languages.

You can change the type of a cell by first clicking on a cell to select it, and then choosing the cell's type in the toolbar's dropdown menu showing Markdown or Code.

Markdown cells

Here is a screenshot of a Markdown cell:

Markdown cells

A Markdown cell

The top panel shows the cell in edit mode, while the bottom one shows it in render mode. The edit mode lets you edit the text, while the render mode lets you display the rendered cell. We will explain the differences between these modes in greater detail in the following section.

Code cells

Here is a screenshot of a complex code cell:

Code cells

Structure of a code cell

This code cell contains several parts, as follows:

  • The Prompt number shows the cell's number. This number increases every time you run the cell. Since you can run cells of a notebook out of order, nothing guarantees that code numbers are linearly increasing in a given notebook.
  • The Input area contains a multiline text editor that lets you write one or several lines of code with syntax highlighting.
  • The Widget area may contain graphical controls; here, it displays a slider.
  • The Output area can contain multiple outputs, here:
    • Standard output (text in black)
    • Error output (text with a red background)
    • Rich output (an HTML table and an image here)

The Notebook modal interface

The Notebook implements a modal interface similar to some text editors such as vim. Mastering this interface may represent a small learning curve for some users.

  • Use the edit mode to write code (the selected cell has a green border, and a pen icon appears at the top right of the interface). Click inside a cell to enable the edit mode for this cell (you need to double-click with Markdown cells).
  • Use the command mode to operate on cells (the selected cell has a gray border, and there is no pen icon). Click outside the text area of a cell to enable the command mode (you can also press the Esc key).

Keyboard shortcuts are available in the Notebook interface. Type h to show them. We review here the most common ones (for Windows and Linux; shortcuts for OS X may be slightly different).

Keyboard shortcuts available in both modes

Here are a few keyboard shortcuts that are always available when a cell is selected:

  • Ctrl + Enter: run the cell
  • Shift + Enter: run the cell and select the cell below
  • Alt + Enter: run the cell and insert a new cell below
  • Ctrl + S: save the notebook

Keyboard shortcuts available in the edit mode

In the edit mode, you can type code as usual, and you have access to the following keyboard shortcuts:

  • Esc: switch to command mode
  • Ctrl + Shift + -: split the cell

Keyboard shortcuts available in the command mode

In the command mode, keystrokes are bound to cell operations. Don't write code in command mode or unexpected things will happen! For example, typing dd in command mode will delete the selected cell! Here are some keyboard shortcuts available in command mode:

  • Enter: switch to edit mode
  • or k: select the previous cell
  • or j: select the next cell
  • y / m: change the cell type to code cell/Markdown cell
  • a / b: insert a new cell above/below the current cell
  • x / c / v: cut/copy/paste the current cell
  • dd: delete the current cell
  • z: undo the last delete operation
  • Shift + =: merge the cell below
  • h: display the help menu with the list of keyboard shortcuts

Spending some time learning these shortcuts is highly recommended.

References

Here are a few references:

A crash course on Python

If you don't know Python, read this section to learn the fundamentals. Python is a very accessible language and, if you have ever programmed, it will only take you a few minutes to learn the basics.

Hello world

Open a new notebook and type the following in the first cell:

In [1]: print("Hello world!")
Out[1]: Hello world!

Here is a screenshot:

Hello world

"Hello world" in the Notebook

Tip

Prompt string

Note that the convention chosen in this book is to show Python code (also called the input) prefixed with In [x]: (which shouldn't be typed). This is the standard IPython prompt. Here, you should just type print("Hello world!") and then press Shift + Enter.

Congratulations! You are now a Python programmer.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You will also find the book's code on this GitHub repository: https://github.com/ipython-books/minibook-2nd-code.

Variables

Let's use Python as a calculator.

In [2]: 2 * 2
Out[2]: 4

Here, 2 * 2 is an expression statement. This operation is performed, the result is returned, and IPython displays it in the notebook cell's output.

Tip

Division

In Python 3, 3 / 2 returns 1.5 (floating-point division), whereas it returns 1 in Python 2 (integer division). This can be source of errors when porting Python 2 code to Python 3. It is recommended to always use the explicit 3.0 / 2.0 for floating-point division (by using floating-point numbers) and 3 // 2 for integer division. Both syntaxes work in Python 2 and Python 3. See http://python3porting.com/differences.html#integer-division for more details.

Other built-in mathematical operators include +, -, ** for the exponentiation, and others. You will find more details at https://docs.python.org/3/reference/expressions.html#the-power-operator.

Variables form a fundamental concept of any programming language. A variable has a name and a value. Here is how to create a new variable in Python:

In [3]: a = 2

And here is how to use an existing variable:

In [4]: a * 3
Out[4]: 6

Several variables can be defined at once (this is called unpacking):

In [5]: a, b = 2, 6

There are different types of variables. Here, we have used a number (more precisely, an integer). Other important types include floating-point numbers to represent real numbers, strings to represent text, and booleans to represent True/False values. Here are a few examples:

In [6]: somefloat = 3.1415
        sometext = 'pi is about'  # You can also use double quotes.
        print(sometext, somefloat)  # Display several variables.
Out[6]: pi is about 3.1415

Note how we used the # character to write comments. Whereas Python discards the comments completely, adding comments in the code is important when the code is to be read by other humans (including yourself in the future).

String escaping

String escaping refers to the ability to insert special characters in a string. For example, how can you insert ' and ", given that these characters are used to delimit a string in Python code? The backslash \ is the go-to escape character in Python (and in many other languages too). Here are a few examples:

In [7]: print("Hello \"world\"")
        print("A list:\n* item 1\n* item 2")
        print("C:\\path\\on\\windows")
        print(r"C:\path\on\windows")
Out[7]: Hello "world"
        A list:
        * item 1
        * item 2
        C:\path\on\windows
        C:\path\on\windows

The special character \n is the new line (or line feed) character. To insert a backslash, you need to escape it, which explains why it needs to be doubled as \\.

You can also disable escaping by using raw literals with a r prefix before the string, like in the last example above. In this case, backslashes are considered as normal characters.

This is convenient when writing Windows paths, since Windows uses backslash separators instead of forward slashes like on Unix systems. A very common error on Windows is forgetting to escape backslashes in paths: writing "C:\path" may lead to subtle errors.

You will find the list of special characters in Python at https://docs.python.org/3.4/reference/lexical_analysis.html#string-and-bytes-literals.

Lists

A list contains a sequence of items. You can concisely instruct Python to perform repeated actions on the elements of a list. Let's first create a list of numbers as follows:

In [8]: items = [1, 3, 0, 4, 1]

Note the syntax we used to create the list: square brackets [], and commas , to separate the items.

The built-in function len() returns the number of elements in a list:

In [9]: len(items)
Out[9]: 5

Note

Python comes with a set of built-in functions, including print(), len(), max(), functional routines like filter() and map(), and container-related routines like all(), any(), range(), and sorted(). You will find the full list of built-in functions at https://docs.python.org/3.4/library/functions.html.

Now, let's compute the sum of all elements in the list. Python provides a built-in function for this:

In [10]: sum(items)
Out[10]: 9

We can also access individual elements in the list, using the following syntax:

In [11]: items[0]
Out[11]: 1
In [12]: items[-1]
Out[12]: 1

Note that indexing starts at 0 in Python: the first element of the list is indexed by 0, the second by 1, and so on. Also, -1 refers to the last element, -2 to the penultimate element, and so on.

The same syntax can be used to alter elements in the list:

In [13]: items[1] = 9
         items
Out[13]: [1, 9, 0, 4, 1]

We can access sublists with the following syntax:

In [14]: items[1:3]
Out[14]: [9, 0]

Here, 1:3 represents a slice going from element 1 included (this is the second element of the list) to element 3 excluded. Thus, we get a sublist with the second and third element of the original list. The first-included/last-excluded asymmetry leads to an intuitive treatment of overlaps between consecutive slices. Also, note that a sublist refers to a dynamic view of the original list, not a copy; changing elements in the sublist automatically changes them in the original list.

Python provides several other types of containers:

  • Tuples are immutable and contain a fixed number of elements:
    In [15]: my_tuple = (1, 2, 3)
             my_tuple[1]
    Out[15]: 2
    
  • Dictionaries contain key-value pairs. They are extremely useful and common:
    In [16]: my_dict = {'a': 1, 'b': 2, 'c': 3}
             print('a:', my_dict['a'])
    Out[16]: a: 1
    In [17]: print(my_dict.keys())
    Out[17]: dict_keys(['c', 'a', 'b'])
    

    There is no notion of order in a dictionary. However, the native collections module provides an OrderedDict structure that keeps the insertion order (see https://docs.python.org/3.4/library/collections.html).

  • Sets, like mathematical sets, contain distinct elements:
    In [18]: my_set = set([1, 2, 3, 2, 1])
             my_set
    Out[18]: {1, 2, 3}
    

    Note

    A Python object is mutable if its value can change after it has been created. Otherwise, it is immutable. For example, a string is immutable; to change it, a new string needs to be created. A list, a dictionary, or a set is mutable; elements can be added or removed. By contrast, a tuple is immutable, and it is not possible to change the elements it contains without recreating the tuple. See https://docs.python.org/3.4/reference/datamodel.html for more details.

Loops

We can run through all elements of a list using a for loop:

In [19]: for item in items:
             print(item)
Out[19]: 1
         9
         0
         4
         1

There are several things to note here:

  • The for item in items syntax means that a temporary variable named item is created at every iteration. This variable contains the value of every item in the list, one at a time.
  • Note the colon : at the end of the for statement. Forgetting it will lead to a syntax error!
  • The statement print(item) will be executed for all items in the list.
  • Note the four spaces before print: this is called the indentation. You will find more details about indentation in the next subsection.

Python supports a concise syntax to perform a given operation on all elements of a list, as follows:

In [20]: squares = [item * item for item in items]
         squares
Out[20]: [1, 81, 0, 16, 1]

This is called a list comprehension. A new list is created here; it contains the squares of all numbers in the list. This concise syntax leads to highly readable and Pythonic code.

Indentation

Indentation refers to the spaces that may appear at the beginning of some lines of code. This is a particular aspect of Python's syntax.

In most programming languages, indentation is optional and is generally used to make the code visually clearer. But in Python, indentation also has a syntactic meaning. Particular indentation rules need to be followed for Python code to be correct.

In general, there are two ways to indent some text: by inserting a tab character (also referred to as \t), or by inserting a number of spaces (typically, four). It is recommended to use spaces instead of tab characters. Your text editor should be configured such that the Tab key on the keyboard inserts four spaces instead of a tab character.

In the Notebook, indentation is automatically configured properly; so you shouldn't worry about this issue. The question only arises if you use another text editor for your Python code.

Finally, what is the meaning of indentation? In Python, indentation delimits coherent blocks of code, for example, the contents of a loop, a conditional branch, a function, and other objects. Where other languages such as C or JavaScript use curly braces to delimit such blocks, Python uses indentation.

Conditional branches

Sometimes, you need to perform different operations on your data depending on some condition. For example, let's display all even numbers in our list:

In [21]: for item in items:
             if item % 2 == 0:
                 print(item)
Out[21]: 0
         4

Again, here are several things to note:

  • An if statement is followed by a boolean expression.
  • If a and b are two integers, the modulo operand a % b returns the remainder from the division of a by b. Here, item % 2 is 0 for even numbers, and 1 for odd numbers.
  • The equality is represented by a double equal sign == to avoid confusion with the assignment operator = that we use when we create variables.
  • Like with the for loop, the if statement ends with a colon :.
  • The part of the code that is executed when the condition is satisfied follows the if statement. It is indented. Indentation is cumulative: since this if is inside a for loop, there are eight spaces before the print(item) statement.

Python supports a concise syntax to select all elements in a list that satisfy certain properties. Here is how to create a sublist with only even numbers:

In [22]: even = [item for item in items if item % 2 == 0]
         even
Out[22]: [0, 4]

This is also a form of list comprehension.

Functions

Code is typically organized into functions. A function encapsulates part of your code. Functions allow you to reuse bits of functionality without copy-pasting the code. Here is a function that tells whether an integer number is even or not:

In [23]: def is_even(number):
             """Return whether an integer is even or not."""
             return number % 2 == 0

There are several things to note here:

  • A function is defined with the def keyword.
  • After def comes the function name. A general convention in Python is to only use lowercase characters, and separate words with an underscore _. A function name generally starts with a verb.
  • The function name is followed by parentheses, with one or several variable names called the arguments. These are the inputs of the function. There is a single argument here, named number.
  • No type is specified for the argument. This is because Python is dynamically typed; you could pass a variable of any type. This function would work fine with floating point numbers, for example (the modulo operation works with floating point numbers in addition to integers).
  • The body of the function is indented (and note the colon : at the end of the def statement).
  • There is a docstring wrapped by triple quotes """. This is a particular form of comment that explains what the function does. It is not mandatory, but it is strongly recommended to write docstrings for the functions exposed to the user.
  • The return keyword in the body of the function specifies the output of the function. Here, the output is a Boolean, obtained from the expression number % 2 == 0. It is possible to return several values; just use a comma to separate them (in this case, a tuple of Booleans would be returned).

Once a function is defined, it can be called like this:

In [24]: is_even(3)
Out[24]: False
In [25]: is_even(4)
Out[25]: True

Here, 3 and 4 are successively passed as arguments to the function.

Positional and keyword arguments

A Python function can accept an arbitrary number of arguments, called positional arguments. It can also accept optional named arguments, called keyword arguments. Here is an example:

In [26]: def remainder(number, divisor=2):
             return number % divisor

The second argument of this function, divisor, is optional. If it is not provided by the caller, it will default to the number 2, as shown here:

In [27]: remainder(5)
Out[27]: 1

There are two equivalent ways of specifying a keyword argument when calling a function. They are as follows:

In [28]: remainder(5, 3)
Out[28]: 2
In [29]: remainder(5, divisor=3)
Out[29]: 2

In the first case, 3 is understood as the second argument, divisor. In the second case, the name of the argument is given explicitly by the caller. This second syntax is clearer and less error-prone than the first one.

Functions can also accept arbitrary sets of positional and keyword arguments, using the following syntax:

In [30]: def f(*args, **kwargs):
             print("Positional arguments:", args)
             print("Keyword arguments:", kwargs)
In [31]: f(1, 2, c=3, d=4)
Out[31]: Positional arguments: (1, 2)
         Keyword arguments: {'c': 3, 'd': 4}

Inside the function, args is a tuple containing positional arguments, and kwargs is a dictionary containing keyword arguments.

Passage by assignment

When passing a parameter to a Python function, a reference to the object is actually passed (passage by assignment):

  • If the passed object is mutable, it can be modified by the function
  • If the passed object is immutable, it cannot be modified by the function

Here is an example:

In [32]: my_list = [1, 2]

         def add(some_list, value):
             some_list.append(value)

         add(my_list, 3)
         my_list
Out[32]: [1, 2, 3]

The add() function modifies an object defined outside it (in this case, the object my_list); we say this function has side-effects. A function with no side-effects is called a pure function: it doesn't modify anything in the outer context, and it deterministically returns the same result for any given set of inputs. Pure functions are to be preferred over functions with side-effects.

Knowing this can help you spot out subtle bugs. There are further related concepts that are useful to know, including function scopes, naming, binding, and more. Here are a couple of links:

Errors

Let's talk about errors in Python. As you learn, you will inevitably come across errors and exceptions. The Python interpreter will most of the time tell you what the problem is, and where it occurred. It is important to understand the vocabulary used by Python so that you can more quickly find and correct your errors.

Let's see the following example:

In [33]: def divide(a, b):
             return a / b
In [34]: divide(1, 0)
Out[34]: ---------------------------------------------------------
         ZeroDivisionError       Traceback (most recent call last)
         <ipython-input-2-b77ebb6ac6f6> in <module>()
         ----> 1 divide(1, 0)

         <ipython-input-1-5c74f9fd7706> in divide(a, b)
               1 def divide(a, b):
         ----> 2     return a / b

         ZeroDivisionError: division by zero

Here, we defined a divide() function, and called it to divide 1 by 0. Dividing a number by 0 is an error in Python. Here, a ZeroDivisionError exception was raised. An exception is a particular type of error that can be raised at any point in a program. It is propagated from the innards of the code up to the command that launched the code. It can be caught and processed at any point. You will find more details about exceptions at https://docs.python.org/3/tutorial/errors.html, and common exception types at https://docs.python.org/3/library/exceptions.html#bltin-exceptions.

The error message you see contains the stack trace, the exception type, and the exception message. The stack trace shows all function calls between the raised exception and the script calling point.

The top frame, indicated by the first arrow ---->, shows the entry point of the code execution. Here, it is divide(1, 0), which was called directly in the Notebook. The error occurred while this function was called.

The next and last frame is indicated by the second arrow. It corresponds to line 2 in our function divide(a, b). It is the last frame in the stack trace: this means that the error occurred there.

We will see later in this chapter how to debug such errors interactively in IPython and in the Jupyter Notebook. Knowing how to navigate up and down in the stack trace is critical when debugging complex Python code.

Object-oriented programming

Object-oriented programming (OOP) is a relatively advanced topic. Although we won't use it much in this book, it is useful to know the basics. Also, mastering OOP is often essential when you start to have a large code base.

In Python, everything is an object. A number, a string, or a function is an object. An object is an instance of a type (also known as class). An object has attributes and methods, as specified by its type. An attribute is a variable bound to an object, giving some information about it. A method is a function that applies to the object.

For example, the object 'hello' is an instance of the built-in str type (string). The type() function returns the type of an object, as shown here:

In [35]: type('hello')
Out[35]: str

There are native types, like str or int (integer), and custom types, also called classes, that can be created by the user.

In IPython, you can discover the attributes and methods of any object with the dot syntax and tab completion. For example, typing 'hello'.u and pressing Tab automatically shows us the existence of the upper() method:

In [36]: 'hello'.upper()
Out[36]: 'HELLO'

Here, upper() is a method available to all str objects; it returns an uppercase copy of a string.

A useful string method is format(). This simple and convenient templating system lets you generate strings dynamically, as shown in the following example:

In [37]: 'Hello {0:s}!'.format('Python')
Out[37]: Hello Python!

The {0:s} syntax means "replace this with the first argument of format(), which should be a string". The variable type after the colon is especially useful for numbers, where you can specify how to display the number (for example, .3f to display three decimals). The 0 makes it possible to replace a given value several times in a given string. You can also use a name instead of a position—for example 'Hello {name}!'.format(name='Python').

Some methods are prefixed with an underscore _; they are private and are generally not meant to be used directly. IPython's tab completion won't show you these private attributes and methods unless you explicitly type _ before pressing Tab.

In practice, the most important thing to remember is that appending a dot . to any Python object and pressing Tab in IPython will show you a lot of functionality pertaining to that object.

Functional programming

Python is a multi-paradigm language; it notably supports imperative, object-oriented, and functional programming models. Python functions are objects and can be handled like other objects. In particular, they can be passed as arguments to other functions (also called higher-order functions). This is the essence of functional programming.

Decorators provide a convenient syntax construct to define higher-order functions. Here is an example using the is_even() function from the previous Functions section:

In [38]: def show_output(func):
             def wrapped(*args, **kwargs):
                 output = func(*args, **kwargs)
                 print("The result is:", output)
             return wrapped

The show_output() function transforms an arbitrary function func() to a new function, named wrapped(), that displays the result of the function, as follows:

In [39]: f = show_output(is_even)
         f(3)
Out[39]: The result is: False

Equivalently, this higher-order function can also be used with a decorator, as follows:

In [40]: @show_output
         def square(x):
             return x * x
In [41]: square(3)
Out[41]: The result is: 9

You can find more information about Python decorators at https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators and at http://www.thecodeship.com/patterns/guide-to-python-function-decorators/.

Python 2 and 3

Let's finish this section with a few notes about Python 2 and Python 3 compatibility issues.

There are still some Python 2 code and libraries that are not compatible with Python 3. Therefore, it is sometimes useful to be aware of the differences between the two versions. One of the most obvious differences is that print is a statement in Python 2, whereas it is a function in Python 3. Therefore, print "Hello" (without parentheses) works in Python 2 but not in Python 3, while print("Hello") works in both Python 2 and Python 3.

There are several non-mutually exclusive options to write portable code that works with both versions:

  • futures: A built-in module supporting backward-incompatible Python syntax
  • 2to3: A built-in Python module to port Python 2 code to Python 3
  • six: An external lightweight library for writing compatible code

Here are a few references:

Going beyond the basics

You now know the fundamentals of Python, the bare minimum that you will need in this book. As you can imagine, there is much more to say about Python.

Following are a few further basic concepts that are often useful and that we cannot cover here, unfortunately. You are highly encouraged to have a look at them in the references given at the end of this section:

  • range and enumerate
  • pass, break, and, continue, to be used in loops
  • Working with files
  • Creating and importing modules
  • The Python standard library provides a wide range of functionality (OS, network, file systems, compression, mathematics, and more)

Here are some slightly more advanced concepts that you might find useful if you want to strengthen your Python skills:

  • Regular expressions for advanced string processing
  • Lambda functions for defining small anonymous functions
  • Generators for controlling custom loops
  • Exceptions for handling errors
  • with statements for safely handling contexts
  • Advanced object-oriented programming
  • Metaprogramming for modifying Python code dynamically
  • The pickle module for persisting Python objects on disk and exchanging them across a network

Finally, here are a few references:

Left arrow icon Right arrow icon

Key benefits

  • • Learn the basics of Python in the Jupyter Notebook
  • • Analyze and visualize data with pandas, NumPy, matplotlib, and seaborn
  • • Perform highly-efficient numerical computations with Numba, Cython, and ipyparallel

Description

Python is a user-friendly and powerful programming language. IPython offers a convenient interface to the language and its analysis libraries, while the Jupyter Notebook is a rich environment well-adapted to data science and visualization. Together, these open source tools are widely used by beginners and experts around the world, and in a huge variety of fields and endeavors. This book is a beginner-friendly guide to the Python data analysis platform. After an introduction to the Python language, IPython, and the Jupyter Notebook, you will learn how to analyze and visualize data on real-world examples, how to create graphical user interfaces for image processing in the Notebook, and how to perform fast numerical computations for scientific simulations with NumPy, Numba, Cython, and ipyparallel. By the end of this book, you will be able to perform in-depth analyses of all sorts of data.

Who is this book for?

This book targets students, teachers, researchers, engineers, analysts, journalists, hobbyists, and all data enthusiasts who are interested in analyzing and visualizing real-world datasets. If you are new to programming and data analysis, this book is exactly for you. If you're already familiar with another language or analysis software, you will also appreciate this introduction to the Python data analysis platform. Finally, there are more technical topics for advanced readers. No prior experience is required; this book contains everything you need to know.

What you will learn

  • • Install Anaconda and code in Python in the Jupyter Notebook
  • • Load and explore datasets interactively
  • • Perform complex data manipulations effectively with pandas
  • • Create engaging data visualizations with matplotlib and seaborn
  • • Simulate mathematical models with NumPy
  • • Visualize and process images interactively in the Jupyter Notebook with scikit-image
  • • Accelerate your code with Numba, Cython, and IPython.parallel
  • • Extend the Notebook interface with HTML, JavaScript, and D3
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 21, 2015
Length: 200 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986989
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Publication date : Oct 21, 2015
Length: 200 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986989
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 7,604.97
Python Machine Learning
₱2500.99
Learning IPython for Interactive Computing and Data Visualization, Second Edition
₱2296.99
IPython Interactive Computing and Visualization Cookbook
₱2806.99
Total 7,604.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Getting Started with IPython Chevron down icon Chevron up icon
2. Interactive Data Analysis with pandas Chevron down icon Chevron up icon
3. Numerical Computing with NumPy Chevron down icon Chevron up icon
4. Interactive Plotting and Graphical Interfaces Chevron down icon Chevron up icon
5. High-Performance and Parallel Computing Chevron down icon Chevron up icon
6. Customizing IPython Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(12 Ratings)
5 star 75%
4 star 0%
3 star 25%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Leif C. Ulstrup Nov 29, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great introduction to using the latest version of iPython (aka jupyter notebook). It is well written with a wide range of examples. The examples are at just the right level to get you started and nudge you in the right direction to explore more. I intend to purchase the author's iPython Cookbook with more in depth examples based on the quality of this book.
Amazon Verified review Amazon
J. Rice Feb 15, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good read. Many good concise examples.
Amazon Verified review Amazon
David E. May 02, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good primer on Jupyter, IPython, and data science learning.
Amazon Verified review Amazon
Jerry Moore Jan 10, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Fun and easy to read. A tutorial.
Amazon Verified review Amazon
ruben Dec 26, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great introduction to using the latest version of iPython. It has many examples all of them start from the beginning to the most dificult ones. The book has a great content very easy to understand. I got this information beause it has the most important thing to apply in development programming and data presentation software.Ruben.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela