Search
Lab - Jupyter notebook tour

Tasks

  • [ ] Run and understand all the Python code on this page

Introduction

This lab is based on A brief tour of the jupyter notebook originally developed by Bryan Engelsen, Steve Nesbitt, Jian Tian.

The following modifications are made by Tom Yeh.

  • updated to Python 3 syntax
  • removed less relevant sections
  • added exercises

This document will give you a brief tour of the capabilities of the IPython notebook.
You can view its contents by scrolling around, or execute each cell by typing Shift-Enter.

You can run shell aliases and magic commands:

pwd
'/Users/tom/baic/book/content/labs/lab-Jupyter_tour'
ls
Python-logo-generic.svg  nyan-cat.png
index.ipynb              python-logo-large.png
message = 'The IPython notebook is great!'
# note: the echo command does not run on Windows, it's a unix command.
!echo $message
The IPython notebook is great!

Plots with matplotlib: do not execute the next below if you do not have matplotlib installed or didn't call the %matplolib magic, as the code will not work.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 3*np.pi, 500)      #linspace gives us 500 equally spaced numbers between 0 and 3*pi
plt.plot(x, np.sin(x**2))
plt.title('looks bumpy');

You can paste blocks of input with prompt markers, such as those from the official Python tutorial

>>> the_world_is_flat = 1
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
Be careful not to fall off!

Python variable types

Strings

Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus ( + ) sign is the string concatenation operator and the asterisk ( * ) is the repetition operator. For example:

str = 'Hola mundo!'

print(str)          # Prints complete string
print(str[0])       # Prints first character of the string
print(str[2:5])    # Prints characters starting from 3rd to 5th
print(str[2:-1])      # Prints string starting from 3rd character
print(str * 2)      # Prints string two times
print(str + "TEST") # Prints concatenated string
Hola mundo!
H
la 
la mundo
Hola mundo!Hola mundo!
Hola mundo!TEST

Numbers

Number data types store numeric values. They are immutable data types which means that changing the value of a number data type results in a newly allocated object.

x=0
a = b = c = 1.53
print(x, a, round(b), int(c))
0 1.53 2 1

Lists

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator. For example:

list = [ 'abcd', 786 , 2.23, 'juan', 70.2 ]
tinylist = [123, 'juan']

print(list)          # Prints complete list
print(list[0])       # Prints first element of the list
print(list[1:3])     # Prints elements starting from 2nd till 3rd 
print(list[2:])      # Prints elements starting from 3rd element
print(tinylist * 2)  # Prints list two times
print(list + tinylist) # Prints concatenated lists
['abcd', 786, 2.23, 'juan', 70.2]
abcd
[786, 2.23]
[2.23, 'juan', 70.2]
[123, 'juan', 123, 'juan']
['abcd', 786, 2.23, 'juan', 70.2, 123, 'juan']

Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example:

tuple = ( 'abcd', 786 , 2.23, 'sonia', 70.2  )
tinytuple = (123, 'sonia')

print(tuple)           # Prints complete list
print(tuple[0])        # Prints first element of the list
print(tuple[1:3])      # Prints elements starting from 2nd till 3rd 
print(tuple[2:])       # Prints elements starting from 3rd element
print(tinytuple * 2)   # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists
('abcd', 786, 2.23, 'sonia', 70.2)
abcd
(786, 2.23)
(2.23, 'sonia', 70.2)
(123, 'sonia', 123, 'sonia')
('abcd', 786, 2.23, 'sonia', 70.2, 123, 'sonia')

Dictionaries

Python's dictionaries are kind of hash table type. They work like structures in MATLAB or IDL, and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.

Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces ( [] ). For example:

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict['one'])       # Prints value for 'one' key
print(dict[2])           # Prints value for 2 key
print(tinydict)          # Prints complete dictionary
print(tinydict.keys())   # Prints all the keys
print(tinydict.values()) # Prints all the values
This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])

Non-blocking output of kernel

If you execute the next cell, you will see the output arriving as it is generated, not all at the end.

import time, sys
for i in range(8):
    print(i, time.sleep(0.5))
0 None
1 None
2 None
3 None
4 None
5 None
6 None
7 None

Markdown cells can contain formatted text and code

You can italicize, boldface

  • build
  • lists

and embed code meant for illustration instead of execution in Python:

def f(x):
    """a docstring"""
    return x**2

or other languages:

if (i=0; i<n; i++) {
  printf("hello %d\n", i);
  x += 4;
}

Courtesy of MathJax, you can include mathematical expressions both inline: $e^{i\pi} + 1 = 0$ and displayed:

$$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$

Rich displays: include anyting a browser can show

Note that we have an actual protocol for this, see the display_protocol notebook for further details.

Images

from IPython.core.display import Image
Image(filename='nyan-cat.png')

An image can also be displayed from raw data or a url

Image('python-logo-large.png')

SVG images are also supported out of the box (since modern browsers do a good job of rendering them):

from IPython.core.display import SVG
SVG(filename='python-logo-generic.svg')
image/svg+xml

Mathematics

And we also support the display of mathematical expressions typeset in LaTeX, which is rendered in the browser thanks to the MathJax library.

Note that this is different from the above examples. Above we were typing mathematical expressions in Markdown cells (along with normal text) and letting the browser render them; now we are displaying the output of a Python computation as a LaTeX expression wrapped by the Math() object so the browser renders it:

from IPython.core.display import Math
Math(r'$F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$')
$\displaystyle F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$