Run Python code using Jupyter Notebook

Anaconda is the most popular Python/R data science distribution which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science such as numpy, pandas, scikit-learn, etc.

It is also the recommended way to install Jupyter Notebook.

After reading this post, you will know:

  • How to install Anaconda on Mac OS X
  • Start Jupyter Notebook and run python scripts

Let’s get started.

Install Anaconda on Mac OS X

  1. Go to the Anaconda Website and choose Python 3.x graphical installer
  2. Complete the installation steps
  3. Verify your installation

Open your terminal and type the following command

python --version

If you chose Python 3.x installer, you should get an output similar to the following

Python 3.6.3 :: Anaconda, Inc.

Start Jupyter Notebook

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text.

Using the command line

  • Type the following command in your terminal

jupyter notebook

Using Anaconda Navigator

  • Open Anaconda Navigator desktop tool
  • Click the Jupyter launch button

Run Python scripts

  • Launch Jupyter Notebook
  • Create a new notebook (.ipynb)
  • Select New -> Python 3 from the top right menu
  • Each notebook comprises cells where you can type code or text (markdown)
  • Type the following python snippet inside your In [ ] cell

average = (12 + 5 + 4) / 3
  • To execute your first python script, hit Shift + Enter
  • Note: Enter key will return a new line
  • Click File -> Save and Checkpoint to save your work

Execution order of Jupyter cells

  • When you create a new Jupyter notebook or open an existing notebook, a new kernel session is created
  • If you have multiple cells of code blocks, it has to be executed in order
  • Running cell 5 before cell 1 may throw an error because variables wouldn’t be defined
  • To restart the current session, click Kernel -> Restart

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *