Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Jupyter notebook atms391geodata/Week 1/Week 1 Exercise 1 scripts_examples_notebook_tour.ipynb

Views: 2162
Kernel: Python 2

A brief tour of the jupyter notebook

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. After you conclude this brief high-level tour, you should read the accompanying notebook titled 01_notebook_introduction, which takes a more step-by-step approach to the features of the system.

The rest of the notebooks in this directory illustrate various other aspects and capabilities of the IPython notebook; some of them may require additional libraries to be executed.

NOTE: This notebook must be run from its own directory, so you must cd to this directory and then start the notebook, but do not use the --notebook-dir option to run it from another location.

You can run shell aliases and magic commands:

pwd
u'/projects/ec668d8e-fd80-4a5e-80ae-f7ac15b9906a/atms391geodata/Week 1'
ls
DUE_DATE.txt DUE_DATE.txt~ Homework 1: Basic python notebook.ipynb Homework 1: Basic python notebook.ipynb~ nyan-cat.png python-logo-generic.svg python-logo-large.png Week 1 Exercise 1 scripts_examples_notebook_tour.html Week 1 Exercise 1 scripts_examples_notebook_tour.ipynb Week 1 Exercise 1 scripts_examples_notebook_tour.ipynb~ Week 1 Exercise 2 notebook_introduction.ipynb Week 1 Exercise 3 variables_strings_numbers.ipynb Week 1 Exercise 4 introducing_functions.ipynb
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');
Image in a Jupyter notebook

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.0 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')

Following is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-9dccc7681e60> in <module>() 1 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) 2 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] ----> 3 tuple[2] = 1000 # Invalid syntax with tuple 4 list[2] = 1000 # Valid syntax with list TypeError: 'tuple' object does not support item assignment

####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 {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']

####Converting between types

FunctionDescription
int(x [,base])Converts x to an integer. base specifies the base if x is a string.
long(x [,base])Converts x to a long integer. base specifies the base if x is a string.
float(x)Converts x to a floating-point number.
complex(real [,imag])Creates a complex number.
str(x)Converts object x to a string representation.
repr(x)Converts object x to an expression string.
eval(str)Evaluates a string and returns an object.
tuple(s)Converts s to a tuple.
list(s)Converts s to a list.
set(s)Converts s to a set.
dict(d)Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s)Converts s to a frozen set.
chr(x)Converts an integer to a character.
unichr(x)Converts an integer to a Unicode character.
ord(x)Converts a single character to its integer value.
hex(x)Converts an integer to a hexadecimal string.
oct(x)Converts an integer to an octal string.

###Errors Errors are shown in informative ways:

run non_existent_file
File "<ipython-input-10-ed740ad8bd14>", line 1 run non_existent_file ^ SyntaxError: invalid syntax
x = 1 y = 4 z = y/(1-x)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-11-dc39888fd1d2> in <module>() 1 x = 1 2 y = 4 ----> 3 z = y/(1-x) ZeroDivisionError: integer division or modulo by zero

When IPython needs to display additional information (such as providing details on an object via x? it will automatically invoke a pager at the bottom of the screen:

magic

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 1 2 3 4 5 6 7

Clean crash and restart

We call the low-level system libc.time routine with the wrong argument via ctypes to segfault the Python interpreter:

from ctypes import CDLL # This will crash a linux system; equivalent calls can be made on Windows or Mac libc = CDLL("libc.so.6") libc.time(-1) # BOOM!!

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: eiπ+1=0e^{i\pi} + 1 = 0 and displayed:

ex=∑i=0∞1i!xie^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')
Image in a Jupyter notebook

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

Image('python-logo-large.png')
Image in a Jupyter notebook

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 in a Jupyter notebook

Video

And more exotic objects can also be displayed, as long as their representation supports the IPython display protocol.

For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):

from IPython.lib.display import YouTubeVideo # a talk about IPython at Sage Days at U. Washington, Seattle. # Video credit: William Stein. YouTubeVideo('1j_HxD4iLn8')

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$')
F(k)=∫−∞∞f(x)e2πikdxF(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx

Loading external codes

In this notebook we've kept the output saved so you can see the result, but you should run the next cell yourself (with an active internet connection).

# %load http://matplotlib.org/1.2.1/mpl_examples/pylab_examples/integral_demo.py #!/usr/bin/env python # implement the example graphs/integral from pyx from pylab import * from matplotlib.patches import Polygon def func(x): return (x-3)*(x-5)*(x-7)+85 ax = subplot(111) a, b = 2, 9 # integral area x = arange(0, 10, 0.01) y = func(x) plot(x, y, linewidth=1) # make the shaded region ix = arange(a, b, 0.01) iy = func(ix) verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] poly = Polygon(verts, facecolor='0.8', edgecolor='k') ax.add_patch(poly) text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', fontsize=20) axis([0,10, 0, 180]) figtext(0.9, 0.05, 'x') figtext(0.1, 0.9, 'y') ax.set_xticks((a,b)) ax.set_xticklabels(('a','b')) ax.set_yticks([]) show()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-20-e181747b0e6d> in <module>() 19 ix = arange(a, b, 0.01) 20 iy = func(ix) ---> 21 verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] 22 poly = Polygon(verts, facecolor='0.8', edgecolor='k') 23 ax.add_patch(poly) TypeError: 'list' object is not callable
Image in a Jupyter notebook
#!/usr/bin/env python # implement the example graphs/integral from pyx from pylab import * from matplotlib.patches import Polygon def func(x): return (x-3)*(x-5)*(x-7)+85 ax = subplot(111) a, b = 2, 9 # integral area x = arange(0, 10, 0.01) y = func(x) plot(x, y, linewidth=1) # make the shaded region ix = arange(a, b, 0.01) iy = func(ix) verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] poly = Polygon(verts, facecolor='0.8', edgecolor='k') ax.add_patch(poly) text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', fontsize=20) axis([0,10, 0, 180]) figtext(0.9, 0.05, 'x') figtext(0.1, 0.9, 'y') ax.set_xticks((a,b)) ax.set_xticklabels(('a','b')) ax.set_yticks([]) show()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-766c9cf4d8d7> in <module>() 18 ix = arange(a, b, 0.01) 19 iy = func(ix) ---> 20 verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] 21 poly = Polygon(verts, facecolor='0.8', edgecolor='k') 22 ax.add_patch(poly) TypeError: 'list' object is not callable
Image in a Jupyter notebook