Python 101 - An Intro to Jupyter Notebook

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain code, equations, visualizations, and formatted text. By default, Jupyter Notebook runs Python out of the box. Additionally, Jupyter Notebook supports many other programming languages via extensions. You can use the Jupyter Notebook for data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more!

In this chapter, you will learn about the following:

  • Installing The Jupyter Notebook
  • Creating a Notebook
  • Adding Content
  • Adding Markdown Content
  • Adding an Extension
  • Exporting Notebooks to Other Formats

This chapter is not meant to be a comprehensive tutorial on the Jupyter Notebook. Instead, it will show you the basics of how to use a Notebook and why it might be useful. If you are intrigued by this technology, you might want to check out my book on the topic, Jupyter Notebook 101.

Let's get started!

Installing The Jupyter Notebook

Jupyter Notebook does not come with Python. You will need to install it using pip. If you are using Anaconda instead of the official Python, then Jupyter Notebook comes with Anaconda, pre-installed.

Here is how you would install Jupyter Notebook with pip:

python3 -m pip install jupyter

When you install Jupyter Notebook, it will install a lot of other dependencies. You may want to install Jupyter Notebook into a Python virtual environment. See Chapter 21 for more information.

Once the installation is done, you are ready to create a Jupyter Notebook!

Creating a Notebook

Creating a Notebook is a fundamental concept. Jupyter Notebook operates through its own server, which comes included with your installation. To be able to do anything with Jupyter, you must first launch this Jupyter Notebook Server by running the following command:

jupyter notebook

This command will either launch your default browser or open up a new tab, depending on whether your browser is already running or not. In both cases you will soon see a new tab that points to the following URL: http://localhost:8888/tree. Your browser should load up to a page that looks like this:

Jupyter Server

Jupyter Server

Here you can create a Notebook by clicking the New button on the right:

Creating a Jupyter Notebook

Creating a Jupyter Notebook

You can create a Notebook with this menu as well as a text file, a folder, and an in-browser terminal session. For now, you should choose the Python 3 option.

Having done that, a new tab will open with your new Notebook loaded:

A new Notebook

A New Notebook

Now let's learn about how to interact with the Notebook!

Naming Your Notebook

The top of the Notebook says that it is Untitled. To fix that, all you need to do is click on the word Untitled and an in-browser dialog will appear:

Renaming a Notebook

Renaming a Notebook

When you rename the Notebook, it will also rename the file that the Notebook is saved to so that it matches the name you gave it. You can name this Notebook "Hello World".

Running Cells

Jupyter Notebook cells are where the magic happens. This is where you can create content and interactive code. By default, the Notebook will create cells in code mode. That means that it will allow you to write code in whichever kernel you chose when you created the Notebook. A kernel refers to the programming language that you chose when creating your Jupyter Notebook. You chose Python 3 when you created this Notebook, so you can write Python 3 code in the cell.

Right now the cell is empty, so it doesn't do anything at all. Let's add some code to change that:

print('Hello from Python!')

To execute the contents of a cell, you need to run that cell. After selecting the cell, there are three ways of running it:

  • Clicking the Run button in the row of buttons along the top
  • Navigating to Cell -> Run Cells from the Notebook menu
  • Using the keyboard shortcut: Shift+Enter

When you run this cell, the output should look like this:

Running a Jupyter Notebook Cell

Running a Jupyter Notebook Cell

Jupyter Notebook cells remember the order in which they are run. If you run the cells out of order, you may end up with errors because you haven't imported something in the right order. However, when you do run the cells in order, you can write imports in one cell and still use those imports in later cells. Notebooks make it simple to keep logical pieces of the code together. In fact, you can put explanatory cells, graphs and more between the code cells and the code cells will still share with each other.

When you run a cell, there are some brackets next to the cell that will fill-in with a number. This indicates the order in which the cells were run. In this example, when you ran the first cell, the brackets filled in with the number one. Because all code cells in a notebook operate on the same global namespace, it is important to be able to keep track of the order of execution of your code cells.

Learning About the Menus

There is a menu in the Jupyter Notebook that you can use to work with your Notebook. The menu runs along the top of the Notebook. Here are your menu options:

  • File
  • Edit
  • View
  • Insert
  • Cell
  • Kernel
  • Widgets
  • Help

Let's go over each of these menus. You don't need to know about every single option in these menus to start working with Jupyter, so this will be a high-level overview.

The File menu is used for opening a Notebook or creating a new one. You can also rename the Notebook here. One of the nice features of Notebooks is that you can create Checkpoints. Checkpoints allow you to rollback to a previous state. To create a Checkpoint, go in the File menu and choose the Save and Checkpoint option.

The Edit menu contains your regular cut, copy, and paste commands, which you can use on a cell level. You can also delete, split, or merge cells from here. Finally, you can use this menu to reorder the cells.

You will find that some of the options here are grayed out. The reason an item is grayed out is because that option does not apply to the currently selected cell in your Notebook. For example, if you selected a code cell, you won't be able insert an image. Try changing the cell type to Markdown to see how the options change.

The View menu is used for toggling the visibility of the header and the toolbar. This is also where you would go to toggle Line Numbers on or off.

The Insert menu is used for inserting cells above or below the currently selected cell.

The Cell menu is useful for running one cell, a group of cells or everything in the Notebook! You can change the cell type here, but you will probably find that the toolbar is more intuitive to use then the menu for that sort of thing.

Another useful feature of the Cell menu is that you can use it to clear the cell's output. A lot of people share their Notebooks with others. If you want to do that, it can be useful to clear out the outputs of the cells so that your friends or colleagues can run the cells themselves and discover how they work.

The Kernel menu is for working with the Kernel itself. The Kernel refers to the programming language plugin. You will occasionally need to restart, reconnect or shut down your kernel. You can also change which kernel is running in your Notebook.

You won't use the Kernel menu all that often. However, when you need to do some debugging in Jupyter Notebook, it can be handy to restart the Kernel rather than restarting the entire server.

The Widgets menu is for clearing and saving widget state. A Widget is a way to add dynamic content to your Notebook, like a button or slider. These are written in JavaScript under the covers.

The last menu is the Help menu. This is where you will go to learn about the special keyboard shortcuts for your Notebook. It also provides a user interface tour and plenty of reference material that you can use to learn how to better interact with your Notebook.

Now let's learn how to create content in your Notebook!

Adding Content

You can choose between two primary types of content for your Notebooks:

  • Code
  • Markdown

There are technically two other cell types you can choose. One is Raw NBConvert, which is only intended for special use cases when using the nbconvert command line tool. This tool is used to convert your Notebook to other formats, such as PDF.

The other type is Heading, which actually isn't used anymore. If you choose this cell type, you will receive the following dialog:

Heading Types

Heading Types

You have already seen how to use the default cell type, Code. So the next section will focus on Markdown.

Creating Markdown Content

The Markdown cell type allows you to format your text. You can create headings, add images and links, and format your text with italics, bold, etc.

This chapter won't cover everything you can do with Markdown, but it will teach you the basics. Let's take a look at how to do a few different things!

Formatting Your Text

If you would like to add italics to your text, you can use single underscores or single asterisks. If you would rather bold your text, then you double the number of asterisks or underscores.

Here are a couple of examples:

You can italicize like *this* or _this_

Or bold like **this** or __this__

Try setting your Notebook cell to Markdown and adding the text above to it. You will then see that the Notebook is automatically formatting the text for you:

Formatting text

Formatting text

When you run the cell, it will format the text nicely:

Formatted Text (after run)

Formatted Text (after run)

If you need to edit the cell again, you can double-click the cell and it will go back into editing mode.

Now let's find out how to add heading levels!

Using Headings

Headings are good for creating sections in your Notebook, just like they are when you are creating a web page or a document in Microsoft Word. To create headings in Markdown, you can use one or more # signs.

Here are some examples:

# Heading 1
## Heading 2
### Heading 3
#### Heading 4

If you add the code above to a Markdown cell in your Notebook, it will look like this:

Markdown Headings

Markdown Headings

You can see that the Notebook is already generating a type of preview for you here by shrinking the text slightly for each heading level.

When you run the cell, you will see something like the following:

Markdown Headings (after running)

Markdown Headings (after running)

As you can see, Jupyter nicely formats your text as different-level headings that can be helpful to structure your text.

Adding a Listing

Creating a listing or bullet points is pretty straight-forward in Markdown. To create a listing, you add an asterisk (*) or a dash (-) to the beginning of the line.

Here is an example:

* List item 1
 * sub item 1
 * sub item 2
* List item 2
* List item 3

Let's add this code to your Notebook:

Adding Listings in Markdown

Adding Listings in Markdown

You don't really get a preview of listings this time, so let's run the cell to see what you get:

Listings in Markdown (after run)

Listings in Markdown (after run)

That looks pretty good! Now let's find out how to get syntax highlighting for your code!

Highlighting Code Syntax

Notebooks already allow you to show and run code and they even show syntax highlighting. However, this only works for the Kernels or languages installed in Jupyter Notebook.

If you want to show code for another language that is not installed or if you want to show syntax highlighting without giving the user the ability to run the code, then you can use Markdown for that.

To create a code block in Markdown, you would need to use 3 backticks followed by the language that you want to show. If you want to do inline code highlighting, then surround the code snippet with single backticks. However, keep in mind that inline code doesn't support syntax highlighting.

Here are two examples in the Notebook:

Syntax Highlighting in Markdown

Syntax Highlighting in Markdown

When you run the cell, the Notebook transforms the Markdown into the following:

Syntax Highlighting (after run)

Syntax Highlighting (after run)

Here you can see how the code now has syntax highlighting.

Now let's learn how to generate a hyperlink!

Creating a Hyperlink

Creating hyperlinks in Markdown is quite easy. The syntax is as follows:

[text](URL)

So if you wanted to link to Google, you would do this:

[Google](https://www.google.com)

Here is what the code looks like in the Notebook:

Hypterlink Markdown

Hyperlink Markdown

When you run the cell, you will see the Markdown turned into a regular hyperlink:

Hyperlink Markdown (after run)

Hyperlink Markdown (after run)

As you can see, the Markdown has been transformed into a traditional hyperlink.

Let's find out about Jupyter extensions next!

Adding an Extension

Jupyter Notebook has lots of functionality right out of the box. If you need anything beyond that, you can also add new features through extensions from a large extension ecosystem. There are four different types of extensions available:

  • Kernel
  • IPython kernel
  • Notebook
  • Notebook server

Most of the time, you will want to install a Notebook extension.

An extension for Jupyter Notebook is technically a JavaScript module that will be loaded in the Notebook's front-end to add new functionality or make the Notebook look different. If you know JavaScript, you can write your own extension!

If you need to add something new to Jupyter Notebook, you should use Google to see if someone has written something that will work for you. The most popular extension is actually a large set of extensions called jupyter_contrib_nbextensions which you can get here:

Most good extensions can be installed using pip. For example, to install the one mentioned above, you can run this command:

$ pip install jupyter_contrib_nbextensions

There are a few that are not compatible with pip. In those cases, you can use Jupyter itself to install the extension:

$ jupyter nbextension install NAME_OF_EXTENSION

While this installs the extension for Jupyter to use, it does not make the extension active yet. You will need to enable an extension if you install it using this method before you can use it.

To enable an extension, you need to run the following command:

$ jupyter nbextension enable NAME_OF_EXTENSION

If you installed the extension while you were running Jupyter Notebook, you may need to restart the Kernel or the entire server to be able to use the new extension.

You may want to get the Jupyter NbExtensions Configurator extension to help you manage your extensions. It is a neat extension designed for enabling and disabling other extensions from within your Notebook's user interface. It also displays the extensions that you have currently installed.

Exporting Notebooks to Other Formats

After you have created an amazing Notebook, you may want to share it with other people who are not as computer savvy as you are. Jupyter Notebook supports converting the Notebooks to other formats:

  • HTML
  • LaTeX
  • PDF
  • RevealJS
  • Markdown
  • ReStructured Text
  • Executable script

You can convert a Notebook using the nbconvert tool that was installed when you originally installed Jupyter Notebook. To use nbconvert, you can do the following:

$ jupyter nbconvert <notebook file> --to <output format>

Let's say you want to convert your Notebook to PDF. To do that, you would do this:

$ jupyter nbconvert my_notebook.ipynb --to pdf

You will see some output as it converts the Notebook into a PDF. The nbconvert tool will also display any warnings or errors that it encounters during the conversion. If the process finishes successfully, you will have a my_notebook.pdf file in the same folder as the Notebook file

The Jupyter Notebook provides a simpler way to convert your Notebooks too. You can do so from the File menu within the Notebook itself. You can choose the Download as option to do the conversion.

Depending on the platform that you are on, you may need to install LaTeX or other dependencies to get certain export formats to work properly.

Wrapping Up

The Jupyter Notebook is a fun way to learn how to use Python or machine learning. It is a great way to organize your data so that you can share it with others. You can use it to create presentations, show your work, and run your code.

In this article, you learned about the following:

  • Installing The Jupyter Notebook
  • Creating a Notebook
  • Adding Content
  • Adding Markdown Content
  • Adding an Extension
  • Exporting Notebooks to Other Formats

You should give Jupyter Notebook a try. It's a useful coding environment and well worth your time.

Related Articles

Learn more about what you can do with Jupyter Notebook in these articles:

Copyright © 2021 Mouse Vs Python | Powered by Pythonlibrary