Python for AI: A Crash Course

Nov 16 2024 · Python 3.12, JupyterLab 4.2.4

Lesson 01: Introduction to Python & Jupyter Notebooks

JupyterLab Demo

Episode complete

Play next episode

Next
Transcript

Demo

Now that you’ve installed Python and JupyterLab, it’s time to learn how to use them.

Learning JupyterLab

JupyterLab is the environment where you’ll create and edit notebooks, interactive documents that combine code, text, images, and visualizations. You’ll use JupyterLab throughout this course, so becoming familiar with it is important.

Launching JupyterLab

To launch JupyterLab, enter the following command in your operating system’s command-line interface (PowerShell in Windows, Terminal on macOS or Linux):

jupyter lab

You’ll see a few messages appear on the command line, after which your default web browser will open a new tab or window that looks something like this.

This is the JupyterLab interface as it appears when it first launches. You should see the following:

  • At the top is the menu bar, where you’ll find often-used commands.
  • The left sidebar is for navigating and managing your computer’s filesystem. You’ll use this often to find, open, and manage notebooks. The main work area occupies most of the space currently occupied by the Launcher, and it offers several options for creating new files.

It’s time to create your first notebook!

Your First Notebook

To create a new notebook, click the Python 3 button in the Launcher’s Notebook section. This will create a new notebook, which will look like this:

You’ll see that the Launcher has been replaced with your newly-created notebook. The main work area is now occupied by the new notebook, which has the default filename Untitled.ipynb.

Note:ipynb is the filename extension for Jupyter notebooks. The name comes from the original name: “IPython Notebooks.”

By default, JupyterLab presents a tabbed interface similar to a browser’s, which allows several notebooks to be open simultaneously.

Before you start working with the notebook, save it.

Click the toolbar’s Save button. The Rename file pop-up will appear. Enter a new name for your notebook. If you can’t think of one, My first notebook will do. Then click the Rename button.

It’s time to start coding!

Code Cells

A new notebook starts with a single code cell, where you can enter and execute code. which is a notebook cell that contains and can execute code. By default, notebook cells are code cells.

Enter the following code into the cell:

# A classic program!
print("Hello, Python world!")

Run the code. You can do this by selecting the cell and either:

  • Clicking the Run button in the menu bar or
  • Pressing Shift-Enter on your keyboard.

You’ll see “Hello, Python world!” appear immediately below the code cell, and your notebook will look like this.

When you run a code cell, the code in that cell executes, after which the notebook presents you with a new code cell. If you want to create a new cell without running code, click the + button in the menu bar.

Here’s a quick explanation of the code you just entered and ran:

  • The # symbol starts single-line comments in Python.
  • Python’s print() function prints strings to the console. In Jupyter, anything printed to the console appears immediately after the code cell that generated that output.

Markdown Cells

Notebooks also have Markdown cells, which contain and can render Markdown, a markup language for writing web content that requires less typing than HTML.

Note: Introducing Markdown is beyond the scope of this lesson. If you’re unfamiliar with Markdown, take a look at GitHub’s guide to Markdown, the interactive tutorial at markdowntutorial.com, or the markdown guide at markdownguide.org.

Select the empty cell just below the cell where you entered the code. Change it from a code cell to a Markdown cell by selecting Markdown from the drop-down menu in Jupyter’s menu bar, then enter the following into the new Markdown cell:

# My First Jupyter Notebook

## Introduction
**This** will be the first of _many_ notebooks that I'll use while taking [Kodeco.com's](https://www.kodeco.com/) AI courses!

The notebook should now look like this.

Markdown cells render when you run them. As with code cells, you run a Markdown cell by selecting the cell and either:

  • Clicking the Run button in the menu bar or
  • Pressing Shift-Enter on your keyboard.

Run the Markdown cell. The cell will render its contents, transforming its Markdown into rendered HTML, as shown in the screenshot below.

Double-click it to edit a rendered Markdown cell. The cell’s contents will transform from rendered HTML back into Markdown.

Selecting Cells

You can select a cell by clicking it. Click the Markdown cell you just created. If the Markdown cell is still showing rendered HTML, double-click it to view the cell in Markdown mode.

A selected cell is highlighted by a colored bar to its left and a colored border. It also displays a set of buttons at its upper right corner for copying, moving, or deleting the cell, as well as adding a new cell above or below the current one.

Note: For the shortcuts to work, you must select the cell itself rather than the text inside it.

Notebooks can have any combination of code and Markdown cells. The size of a notebook is limited only by disk space.

Code Cells’ Order of Execution

Note that each executed code cell has a number in the square brackets to its left. The presence of a number indicates that the code in that cell has executed, and that number specifies the order in which the code was executed.

Variable Scope and Displaying Values

If you enter the name of a variable, expression, or object into a code cell and run that cell, the notebook will display Python’s evaluation of that variable, expression or object.

Once you define a variable in a notebook, it’s in scope for code in any cell in the same notebook that you run afterward, as long as:

  • The notebook kernel is active
  • The variable has not been deleted

Cells Can Be Run in Any Order

Like cells in a spreadsheet, cells in a notebook can be run in any order you choose, not just in top-down order. However, it often makes sense to run them in top-down order.

Defining and Redefining Functions

Like variables, once a function is defined by entering it into a cell and running it, it’ll be in scope for any code in the same notebook you run afterward.

You can redefine a function by altering its code and then running its cell. Subsequent calls to that function will use the new function code.

Long-Running Cells

A code cell will display an indicator — the * character inside the [ ] to its left — while running code. You probably won’t see this indicator in a cell with code that executes instantaneously, but you’ll see it for cells with code that runs longer.

While a cell is executing code, no other cell can execute code; they have to wait until the cell currently executing code has finished.

You can interrupt a cell running code by clicking the stop button in the toolbar.

Executing Shell Commands

You can execute shell commands from a code cell. Any line that starts with ! will execute in your operating system’s shell. This is useful for executing pip commands to install Python packages required by a notebook.

Try getting a directory listing using !. If you’re on macOS or Linux, enter the following command into a code cell and run it:

! ls

If you’re running Windows, use this command instead:

! dir

On Windows, JupyterLab sends commands from lines beginning with ! to Command Prompt (the one that runs DOS commands), even if you launched JupyterLab from PowerShell. That’s why the command above was dir and not ls.

To send commands to PowerShell, for instance, the dir command, use this format:

! Powershell.exe -Command "dir"

Restarting the Kernel

There will come a time when, after running several code cells, you may want to re-run your code and have JupyterLab “forget” anything you’ve defined.

newvar = 5
newvar      # prints 5

The simplest way to do this is to restart the kernel, the “engine” that executes the code and manages the state of variables and anything else your code defines. You do this with the restart kernel button in the toolbar. It’s the one with the icon that looks like a browser’s “refresh” button.

Restarting the kernel will bring a notebook back to its initial state. The contents will remain, but any defined variables, functions, classes, and other code will have been “forgotten.”

After a restart, printing newvar results in an error:

newvar      # prints the following error
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 1
----> 1 newvar

NameError: name 'newvar' is not defined

See forum comments
Cinema mode Download course materials from Github
Previous: Intro to Python & JupyterLab Next: Instruction