0% found this document useful (0 votes)
7 views82 pages

MIE1624H Lecture 2 - Python Programming

The document outlines a lecture on Python programming as part of an Introduction to Data Science and Analytics course at the University of Toronto. It covers essential Python concepts such as variables, data types, control flow, functions, and introduces the Pandas library for data manipulation. The lecture also includes practical examples and explanations of Python's arithmetic operators, dictionaries, and assignment statements.

Uploaded by

ltc1143817203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views82 pages

MIE1624H Lecture 2 - Python Programming

The document outlines a lecture on Python programming as part of an Introduction to Data Science and Analytics course at the University of Toronto. It covers essential Python concepts such as variables, data types, control flow, functions, and introduces the Pandas library for data manipulation. The lecture also includes practical examples and explanations of Python's arithmetic operators, dictionaries, and assignment statements.

Uploaded by

ltc1143817203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Oleksandr Romanko, Ph.D.

Associate Director, Financial Risk Quantitative Research, SS&C Algorithmics


Adjunct Professor, University of Toronto

MIE1624H – Introduction to
Data Science and Analytics
Lecture 2 – Python
Programming

University of Toronto
January 14, 2025
Lecture outline

Introduction to Data Science and Analytics (continuing Lecture 1)


Python essentials
▪ IPython notebooks
▪ Modules
▪ Variables and types
▪ Operators and comparisons
▪ Compound types - strings, tuples, lists and dictionaries
▪ Control flow - conditional statements (if, elif, else), loops
▪ Functions
▪ Classes
▪ Files and the operating system
▪ Exception handling

2
Lecture outline

Introduction to Pandas
▪ Introduction to pandas data structures – DataFrame, index objects
▪ Pandas essential functionality
▪ Summarizing and computing descriptive statistics
▪ Pivot tables in pandas

Web-scrapping with Python

3
 Python Essentials
Roadmap
Python essentials
Variables and types
Operators and comparisons
Compound types - strings, tuples, lists and dictionaries
Functions
Modules
Files and the operating system
Control flow - conditional statements (if, elif, else), loops
Exception handling

Introduction to Pandas
Introduction to pandas data structures – DataFrame, index objects
Pandas essential functionality
Summarizing and computing descriptive statistics
Pivot tables in pandas
IPython notebooks
5
Introducing Python

Python is an interpreted language (not a compiled one)

=> you can run code incrementally, one statement at a time

6
Expressions and Values

7
Arithmetic Operators
Operator Operation Expression English description Result

+ addition 11 + 56 11 plus 56 67

- subtraction 23 - 52 23 minus 52 -29

* multiplication 4 * 5 4 multiplied by 5 20

** exponentiation 2 ** 5 2 to the power of 5 32

/ division 9 / 2 9 divided by 2 4.5

// integer division 9 // 2 9 divided by 2 4

% modulo 9 % 2 9 mod 2 1
(remainder) 5
8
Arithmetic Operator Precedence - 1

When multiple operators are combined in a single


expression, the operations are evaluated in order of
precedence.

Operator Precedence

** highest

- (negation)

*, /, //, %

+ (addition), - (subtraction) lowest

9
Arithmetic Operator Precedence - 2
>>> 10 % 3
1
>>> 25 + 30 / 6
30.0
>>> 5 + 4 ** 2
21
>>> 100 - 25 * 3 % 4
97
>>> 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
6.75
10
Types

A type is a set of values and the operations that


can be performed on those values.

11
Types int and float
int: integer
3, 4, 894, 0, -3, -18

float: floating point number (an approximation to a real


number)
5.6, 7.342, 53452.0, 0.0, -89.34, -9.5
>>> 5 + 2 * 4
13
>>> 5.0 + 2 * 4
13.0
>>> 30/6
5.0
>>> 30//6
5 12
Type str - 1
● A string literal is a sequence of characters. A string can
be made up of letters, numbers, and special characters.

● Strings in Python start and end with a single quote (') or


double quotes (").

● If a string begins with a single quote, it must end with a


single quote. The same applies to double-quoted strings.

● The two types of quotes cannot be mixed!

13
Type str - 2

>>> "Hello!"
'Hello!'

>>> 'how are you?'


'how are you?'

>>> 'short- and long-term'


'short- and long-term'

14
Dictionaries -1
• Lists/Tuples/Strings are ordered collections
• Dictionaries are mapped (unordered) collections
- data is accessed using keys
- data is unordered

• Example:
my_dictionary = {key_1:data_1, key_2:data_2,... , key_n:data_n}

key_1 maps to data_1, key_2 maps to data_2, etc.

my_dict = {'Name': 'Jane Smith', 'SN': 990632802, 'Status: 'Registered'}


15
Dictionaries - Properties

A dictionary keeps track of associations between keys and
values
- like a regular dictionary where a key is a word and the
value is the definition of that word.
► This makes look-ups and other operations very easy


Dictionary values can be any Python object (standard objects
or user-defined objects.


Dictionary keys must be immutable objects: strings, numbers,
tuples, etc.:
- no duplicate key is allowed
16
Dictionary Functions
● cmp(dict1, dict2) Compares elements of both dict

● len(dict) Gives the total length of the dictionary,


i.e., the number of items in the dictionary

● str(dict) Produces a string representation of a


dictionary

17
Dictionary Methods
• clear() Removes all elements of the dictionary
• copy() Returns a shallow copy of the dictionary
• fromkeys() Create a new dictionary with keys from seq and
values set to value.
• get(key, Returns the value key maps to or default if key is
default=None) not in the dictionary
• has_key(key) Returns true if key is in the dictionary, false
otherwise
• items() Returns the data in the dictionary as a list of
tuples (key, value)
• keys() Returns the keys in the dictionary as a list
• update(dict2) Adds dict2's key-values pairs
• values() Returns the values in the dictionary as a list 18
● Form to define a dictionary:
my_dict = {key1: value1, key2: value2, ...}
● Form to look up a key's value:
my_dict[key]

Form to add or update a key-value pair:
my_dict[key] = value

Form to delete from a dictionary
del dict['Name'] # remove entry with key 'Name'
[Link]() # remove all entries in dict
del dict # delete entire dictionary
- my_dict is the name of the dictionary object.
- key is any immutable object (string, int, tuple).
19
- value is any Python object.
Example -1
>>> CO2_by_year = {1799:1, 1800:70, 1801:74,
... 1802:82, 1902:215630, 2002:1733297}
>>> # Look up the emissions for the given year

>>> CO2_by_year[1801]
74
>>> # Add another year to the dictionary
>>> CO2_by_year[1950] = 734914
>>> CO2_by_year{1799: 1, 1800: 70, 1801: 74,
... 1802: 82, 1902: 215630, 2002: 1733297,
... 1950: 734914}

20
Example -2
>>> CO2_ by_year[2009] = 1000000
>>> CO2_by_year[2000] = 10
>>> CO2_by_year
{2000: 10, 2002: 1733297, 1799: 1, 1800: 70, 1801: 74, 1802:
82, 2009: 1000000, 1902: 215630}
>>> 1950 in CO2_by_year
False
>>> del CO2_by_year[1950]
>>> len(CO2_by_year) 8
>>> for key in CO2_by_year:
... print(key)
2000
2002
21
...
● How can we iterate through the keys?
for k in [Link]():
print(k)

● How can we iterate through the values?


for v in [Link]():
print(v)

● How can we iterate through the key-value pairs?


for key, value in [Link]():
22
Tuples

Are similar to lists, but cannot be changed
my_tuple = (1, 2, 3)


Useful when we want to group data together, in
assignment statements

23
Sets

Like mathematical sets, they are unordered!
>>> my_set = {1, 2, 3}

>>> x = [1, 2, 3]
>>> my_set = set(x)


An element is either in the set or it is not.
→ efficient membership check
24
Assignment statements - 1

• General form of an assignment statement: variable = expression

• General rule for executing an assignment statement:

1. Evaluate the expression to the right of the = sign.


-produces a memory address of the value the expression evaluates to

2. Store the memory address in the variable on the left of the = sign.

25
Assignment statements - 2
>>> difference = 20
>>> double = 2 * difference
>>> double
40
>>> difference = 5
>>> double
40

● The expression on the right of the = sign is evaluated to 20


● The value 20 will be put at memory address id1.
● The variable on the left of the = sign, difference, will refer
to 20 by storing id1 in difference. 26
Assignment statements - 3
>>> double = 2 * difference
● The expression on the right of the = sign: 2 * difference
is evaluated
=> difference refers to the value 20
=> difference * 20 evaluates to 40.

● The memory address id2 is assigned to the value 40.

● The variable on the left of the = sign, double, will refer to


40 by storing id2.

27
Assignment statements - 4
>>> base = 20
>>> height = 12
>>> area = base * height / 2
>>> area
>>> 120.0
>>> celsius = 22
>>> fahrenheit = celsius * 9/5 + 32
>>> fahrenheit
71.6

28
Assignment statements - 5

Strings can also be stored as variables.

>>> reminder_text = 'Buy groceries after work'


>>> reminder_text
'Buy groceries after work'
>>> str_var = 'Welcome to MIE1624'
>>> str_var
'Welcome to MIE1624'
>>>str_var = "What is 10 * (2 + 9)?"
>>> str_var
'What is 10 * (2 + 9)?' 29
Assignment statements - 6
Strings can also be stored as variables.

>>> reminder_text = 'Please buy groceries after


work'
>>> reminder_text
'Please buy groceries after work'
>>> str_var = 'Welcome to MIE1624'
>>> str_var
'Welcome to MIE1624'
>>>str_var = "What is 10 * (2 + 9)?"
>>> str_var
'What is 10 * (2 + 9)?' 30
Augmented Assignment Operators
>>> number = 3
>>> Number
3
>>> number = 2 * number
>>> number
6
>>> number = number * number
>>> number
36
>>> score = 50 >>> score 50 >>> score = score +
20
31
>>> score 70
Augmented Assignment Operators
Expression Identical English
Operator Expression description
+= x = 7 x = 7 x refers to 9
x += 2 x = x + 2
-= x = 7 x = 7 x refers to 5
x -= 2 x = x - 2
*= x = 7 x = 7 x refers to 14
x *= 2 x = x * 2
/= x = 7 x = 7 x refers to 3.5
x /= 2 x = x / 2
//= x = 7 x = 7 x refers to 3
x //= 2 x = x // 2
%= x = 7 x = 7 x refers to 1
x %= 2 x = x % 2
**= x = 7 x = 7 x refers to 49 2
x **= 2 x = x ** 2 32
9
What is a function?
● A function is a block of organized (reusable) code that is
used to perform an activity.

● In Python a function is implemented as a compound


statement.

● Python has built-in functions, but programmers can also


create their own user-defined functions.

30
33
Defining a Python Function -1
• The general form of a function definition:
def function_name (parameters):
['''function_docstring''']
function_body
[return [expression]]

• A function block begins with the keyword def followed by the


function name and parentheses ( ).

• Parameters/arguments:
-0 or more, separated by a comma, are placed within the
parentheses.
-variables whose values are supplied when the function is called
-by default, parameters have a positional behaviour (exception:
named arguments, which can be given in any order) 34
Defining a Python Function -2
Function body: consists of one or more statements,
● The code block/body within every function starts with a

colon (:) and is indented.


● The first statement of a function can be an optional
statement - the documentation string of the function, a.k.a.
the docstring.
● The statement return[expression]exits if a function
is passing back a value to the caller.
=> A return statement with no arguments is the same as
return None.

35
Using Functions
● Defining a function only gives the function a name,
declares its input parameters and specifies its behaviour,
i.e., the instructions to be performed when the function is
executed => but nothing gets executed yet!

● Once the definition of a function is ready, the function can


be executed by calling it from another function or directly
from the Python prompt.

36
Calling a Function
● The general form of a function call:

function_name(arguments)

● Executing a function call:


> Evaluate the arguments
> Call the function, passing in the argument values
>> the instructions in the body of the function are
carried out

37
Function Design Recipe - Six Steps
1. Pick a meaningful name: a short answer to 'What does the function do'?

2. Prepare the Type Contract and write the function header

> What are the parameter types?


> What type of value is returned?

- Pick meaningful parameter names: it is much easier to understand a function if


the variables have names that reflect their meaning.

3. Prepare a few examples (function calls) - 'What should the function do'?

[Link]: write a docstring describing the function. Mention every parameter in


your description. Describe the return value.

5. Body - Write the body of the function.

6. Test - Run the examples designed in Step 3 to make sure they work as expected.
38
Applying the Design Recipe -1
The United States measures temperature in Fahrenheit and Canada measures it in
Celsius. When travelling between the two countries it helps to have a conversion
function. Write a function that converts from Fahrenheit to Celsius.
1. Pick a name: convert_to_celsius

2. Type Contract and Header (what the function will look like)

Type Contract (number) -> number


Header def convert_to_celsius(fahrenheit):
3. Examples
convert_to_celsius(32) => 0
[Link] Return the number of Celsius degrees
equivalent to Fahrenheit degrees.
5. Body
degrees = (fahrenheit - 32) * 5 / 9
return degrees
39
Applying the Design Recipe -2
Complete function definition
def convert_to_celsius(fahrenheit):
''' (number) -> number
Return the celsius degrees equivalent to
fahrenheit degrees.
'''
celsius = (fahrenheit - 32) * 5 / 9

return celsius
6. Test - run the examples.

>>> convert_to_celsius(32)
0
>>> convert_to_celsius(212)
100 40
Calling functions within other function definitions -1
Let us write a function to convert from hours to seconds.
def convert_to_minutes(num_hours):
"""(number) -> number
Return the number of minutes there are in num_hours
hours.
"""
result = num_hours * 60
return result

def convert_to_seconds(num_hours):
"""(number) -> number
Return the number of seconds there are in num_hours
hours.
"""
return convert_to_minutes(num_hours) * 60
Testing:
>>> convert_to_minutes(2)
120
>>>convert_to_seconds(2)
7200 41
Calling functions within other function definitions -2
def convert_to_celsius(fahrenheit):
''' (number) -> number
Return the number of celsius degrees
equivalent to fahrenheit degrees. '''
degrees = (fahrenheit - 32) * 5 / 9
return degrees

def convert_to_kelvin(fahrenheit):
''' (number) -> number
Return the number of kelvin degrees equivalent to
fahrenheit degrees.
'''
kelvin = convert_to_celsius(fahrenheit) + 273.15
return kelvin

Testing:
>>> convert_to_kelvin(32)
273.15
42
Use Function Calls as Arguments to Other Functions
One triangle has a base of length 3.8 and a height of length 7.0
and a second triangle has a base of length 3.5 and a height of
length 6.8. Find the area of the larger triangle.

The approach: pass calls to function area as arguments to built-in


function max.

>>> max(triangle_area(3.8, 7.0), triangle_area(3.5, 6.8))

43
Modules
● A module is a file containing Python definitions and statements.
● The file name is the module name with the suffix .py appended.

Example: [Link] module
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
[Link](b)
a, b = b, a+b
return result

44
● When needed just: import fibo
Opening Files
• open(filename, mode)
(str,str) -> [Link]
opens the f ile Filename
in the same directory as the .py file
returns a f ile-handle

mode can take several values:


r: open the f ile for reading
w: open the f ile for writing (erasing the content!)
a: open the f ile for writing, appending new

information to the end of the file


45
Opening Files -2

To start using a f ile, given its f ilename , it has to be open. (The
name is a string.)
• To open the f ile, use the function open()
myfile = open("[Link]", "r")
o
open() is a Python function
o
[Link] is the name of the f ile to be open
o myfile is a variable that is assigned the f ile object
returned by open
o r is a string indicating what we wish to do with the f ile.
Options for this string are "r", "w", "a", meaning read,
write or append. The default is "r “

Note: writing to a f ile that already exists, erases the existing content.
Use append if you want to preserve the content. 46
Closing Files

[Link]()

→(NoneType) -> NoneType

→ myf ile is the f ile object returned by open()

47
Reading Files

We call a f ile object that was opened for reading a reader


Various ways to read from a reader:

1. Read lines one at a time from beginning to end:


for line in myf ile:

<statements>

[Link] everything in the f ile at once into a list of strings: read the
whole f ile into list str_ls. Each element of str_ls is a line.
str_ls = [Link]()
print(str_ls) 48
3. Read everything in the f ile at once into a string:
s = [Link]() # Read the whole file into string s.
print(s)

4. Read a certain number of characters:


s = [Link](10) # Read 10 characters into s
print(s)

5. Read a line at a time:


s = [Link]() # Read a line into s.
print(s)
s = [Link]() # Read the next line into s.
print(s) 49
Reading Files - Recap

• [Link]()- read 1 line from the f ile

• [Link]()- read the whole f ile into a single string

• [Link]() - read the whole f ile into a list, with each


element being one line of text

• [Link](n)- read the next N bytes of a f ile,


rounded up to the end of a line.

50
Reading CSV in Python

import csv
...
input_file = open(file_name)
reader = [Link](input_file)
...
for line in reader:
# Read as from an ordinary file, but line
is a list
<process line>
51
Writing to a file


First we open a f ile to write, then we write the
contents
[Link]()

Just like printing, except you have to add your


own newline characters


Close your file
52
 Introduction to Pandas
Lecture outline

Introduction to Pandas
▪ Introduction to pandas data structures – DataFrame, index objects
▪ Pandas essential functionality
▪ Summarizing and computing descriptive statistics
▪ Pivot tables in pandas

Web-scrapping with Python

54
Introduction to Pandas

an open source Python library providing high
performance data structures and analysis tools.

>>> import pandas as pd

>>> import numpy as np

>>> import [Link] as plt

55
Pandas Data Structures -Series
● One-dimensional labeled array

● Holds any data type (integers, strings, floating point numbers,


Python objects, etc.)

● The axis labels are collectively referred to as the index.

>>> s = [Link](data, index=index)

● data: a dictionary, an ndarray, a scalar value (e.g., 11)


● index: is a list of axis labels.

56
Series from from an ndarray
>>> s= [Link]([Link](5), index=['a',
'b','c', 'd', 'e'])
>>> s
a 0.2735
b 0.6052
c -0.1692
d 1.8298
e 0.5432
dtype: float64
>>> [Link]
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

>>> [Link]([Link](5))
0 0.3674
1 -0.8230
2 -1.0295
3 -1.0523
4 -0.8502
dtype: float64 57
Series from from a dictionary
• If an index is passed, the values in data corresponding to the labels in the
index will be pulled out.

• If no index is passed, an index will be constructed from the sorted keys of


the dict, if possible.

>>> d = {'a' : 0., 'b' : 1., 'c' : 2.}


>>> [Link](d)
a 0.0
b 1.0
c 2.0
dtype: float64
>>> [Link](d, index=['b', 'c', 'd', 'a']) b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
58
● NOTE: NaN is the standard missing data marker used in pandas
Series from from a scalar value

If data is a scalar value, an index must be provided. The value will be
repeated to match the length of index
>>> [Link](5., index=['a', 'b', 'c', 'd', 'e'])
a 5.0
b 5.0
c 5.0
d 5.0
e 5.0
dtype: float64

59
Series Behaviour

Series acts very similarly to a ndarray, and is a valid argument to
most NumPy functions.
>>> s[0]
>>> 0.27348116325673794
>>> s[:3]
>>> a 0.2735
b 0.6052
c -0.1692
dtype: float64


A Series is like a fixed-size dict in that you can get and set values
by index label:
>>> s['a']
>>> 0.27348116325673794
>>> s['e'] = 12.
>>> [Link]('a')
>>> 0.27348116325673794
60
DataFrame Objects
● class [Link](data=None, index=None,
columns=None, dtype=None, copy=False)[source]


Two-dimensional, size-mutable, potentially heterogeneous
tabular data structure with labeled rows and columns.

● Dictionar-like container for Series objects.

● Arithmetic operations align on both row and column labels.

61
DataFrame - Parameters
• data : numpy ndarray, dictionary (Series, arrays, constants, or
list-like objects), or DataFrame
• index : index or array-like to use for resulting frame.
• columns : Index or array-like, labels to use for resulting frame.
• dtype : data_type (default None), to force, otherwise infer
• copy : boolean (default False), to copy data from inputs.
>>> d = {'col1': ts1, 'col2': ts2}
>>> df1 = DataFrame(data = d, index = index)
>>> df2 = DataFrame([Link](10, 5))
>>> df3 = DataFrame([Link](10, 5),
columns=['a', 'b', 'c', 'd', 'e'])
● [Link] returns a sample(s) from the 62
“standard normal” distribution.
DataFrames from Series or dictionaries

The result index will be the union of the indexes of the various
Series.
d = {'one' : [Link]([1., 2., 3.], index=['a', 'b', 'c']),
'two' : [Link]([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
>>> df = [Link](d)
>>> df
one two
a 1.0 1.0
b 2.0 2.0
c 3.0 3.0
d NaN 4.0

>>> [Link](d, index=['d', 'b', 'a'])


one two
d NaN 4.0
b 2.0 2.0 63
a 1.0 1.0
Accessing Rows and Columns

The row and column labels can be accessed, respectively,
by accessing the index and columns attributes:
● Note: when a particular set of columns is passed along
with a dict of data, the passed columns override the keys
in the dict.
>>> [Link]
Index([u'a', u'b', u'c', u'd'], dtype='object')
>>> [Link]
Index([u'one', u'two'], dtype='object')

64
Index

Immutable ndarray implementing an ordered, sliceable set. The
basic object storing axis labels for all pandas objects

Parameters:
● data : array-like (1-dimensional)
● dtype : NumPy dtype (default: object)
● copy : bool Make a copy of input ndarray
● name : objectName to be stored in the index
● tupleize_cols : bool (default: True)
When True, attempt to create a MultiIndex if possible

65
Index Attributes

66
Index Methods

67
Reshaping by pivoting DataFrame objects -1
● Reshaping by pivoting DataFrame objects
● Data is often stored in CSV files or databases in so-called
“stacked” or “record” format:
>>> df
date variable value
0 2000-01-03 A 0.469112
1 2000-01-04 A -0.282863
2 2000-01-05 A -1.509059
3 2000-01-03 B -1.135632
4 2000-01-04 B 1.212112
5 2000-01-05 B -0.173215
6 2000-01-03 C 0.119209
7 2000-01-04 C -1.044236
8 2000-01-05 C -0.861849
9 2000-01-03 D -2.104569
10 2000-01-04 D -0.494929
68
11 2000-01-05 D 1.071804
Reshaping by pivoting DataFrame objects -2
● To select out everything for variable A we could do:
>>> df[df['variable'] == 'A']
>>> date variable value
0 2000-01-03 A 0.469112
1 2000-01-04 A -0.282863
2 2000-01-05 A -1.509059

● For time series operations a better representation would have the


columns as unique variables and an index of dates identifying
individual observations.
● To reshape the data use the pivot function:
>>> [Link](index='date', columns='variable', values='value')
>>> variable A B C D
date
2000-01-03 0.469112 -1.135632 0.119209 -2.104569
2000-01-04 -0.282863 1.212112 -1.044236 -0.49492969
2000-01-05 -1.509059 -0.173215 -0.861849 1.071804
Computing Descriptive Statistics
● [Link](percentiles=None, include=None,
exclude=None)[source]
● Generate various summary statistics, excluding NaN values.

Parameters:

percentiles : array-like, optional. The percentiles to include in the
output. Should all be in the interval [0, 1].

include, exclude : list-like, ‘all’, or None (default) Specify the form of
the returned result. Either:
- None to both (default). The result will include only numeric-
typed columns or, if none are, only categorical columns.
- A list of dtypes or strings to be included/excluded.
- If include= ‘all’, the output column-set will match the input one.
Returns: summary statistics 70
Pandas pivot_table
cheat sheet

71
 Jupyter Notebooks
Jupyter Notebook
● An interactive computational environment, in which you
can combine code execution, rich text, mathematics, plots
and multi media.

● Notebook documents ( “notebooks”) are documents


produced by the Jupyter Notebook App
contain: computer code (e.g. python) and rich text
elements (paragraph, equations, figures, links, etc.).

● Notebook documents are both human-readable


documents as well as executable documents which can be
run to perform data analysis.
73
Jupyter Notebook App
● A server-client application that allows editing and
running notebook documents via a web browser.

● The Jupyter Notebook App can be executed on a local


desktop requiring no internet access or can be
installed on a remote server and accessed through the
internet.

● In addition to displaying/editing/running notebook


documents, the App has a “Dashboard” showing local
files and allowing to open notebook documents.
74
Notebook Kernel
A computational engine that executes the code
contained in a Notebook document.

● The kernel associated with a notebook is


automatically launched when the notebook is
opened.

● When the notebook is executed, the kernel


performs the computation and produces the
results.
75
Notebook Dashboard

The Dashboard is the component which is
shown first in the Jupyter App.


Main functionality: open notebook documents,
and to manage the running kernels.


Other features (similar to a file manager):
navigating folders and renaming/deleting files.

76
Running the Jupyter Notebook
● The App can be launched by clicking on the Jupyter
Notebook icon installed by Anaconda in the start menu
(Windows) or by typing in a terminal (cmd on Windows,
Terminal on OSX):
> jupyter notebook

● This will launch a new browser window/tab showing the


Notebook Dashboard
● When started, the App can access only files within its start-
up folder (including any sub-folder).
● If the notebook documents are not in a subfolder of your
user folder further configuration steps are necessary. 77
Shutting Down/Restarting a Kernel
● When a notebook is opened, its kernel is also started.
● Closing the notebook browser tab, will not shut down the
kernel => the kernel needs to be explicitly shut down.
● To shut down a kernel:
(1) go to the associated notebook and click on menu
File ->Close and Halt.
or (2) in the Running tab of the Dashboard (which shows
all the running notebooks/kernels) click on a the
Shutdown button of the kernel you want to stop.
● To restart a kernel click on the menu Kernel -> Restart.
This can be useful to start over a computation from scratch
78
Executing a Notebook
● Launch the App

● In the Dashboard, navigate to find the notebook.

● Click on its name (will open it in a new browser tab).

● Run the notebook step-by-step (one cell a time) by


pressing shift + enter.

● Run a notebook in a single step by clicking on the


79
menu Cell -> Run All.
Shut down the Jupyter Notebook App
● Closing the browser window/tab will not close the
Jupyter Notebook App.
=> to completely shut it down the associated terminal
needs to be closed.

● Many copies of the Jupyter Notebook App can be run


in parallel, but it is not a recommended usage mode.

80
 To Do before Lecture 3
Run IPython examples provided in class
◼ Use Python on cloud via Google Colab
❑ You can use Python on Google cloud via [Link]
◼ Install Python on your laptop
❑ Recommended to use Python version 3.10, 3.11 or 3.12
❑ You may use your own Python distribution, Anaconda distribution is
recommended to install [Link]
◼ Form groups of seven students for in-class presentations and course
project
❑ Add all your group members to Group X on Quercus
❑ All groups should have exactly seven members
❑ In-class presentations will be done in the order of group numbers
❑ Course Project will be the same for all groups
❑ Every group member get the same mark, independently on how you split
responsibilities inside each group
◼ Check class web-page on Quercus regularly

82

You might also like