0% found this document useful (0 votes)
2 views141 pages

Tutorial 1 Introduction To Python

This document is a tutorial for MSBD 5001, Foundations of Data Analytics, focusing on Python, Jupyter Notebook, and related tools. It covers the basics of Python programming, installation of Anaconda, and usage of Jupyter Notebook and JupyterLab for data analysis. Additionally, it introduces Markdown for formatting text in Jupyter notebooks.

Uploaded by

john.lo7242
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)
2 views141 pages

Tutorial 1 Introduction To Python

This document is a tutorial for MSBD 5001, Foundations of Data Analytics, focusing on Python, Jupyter Notebook, and related tools. It covers the basics of Python programming, installation of Anaconda, and usage of Jupyter Notebook and JupyterLab for data analysis. Additionally, it introduces Markdown for formatting text in Jupyter notebooks.

Uploaded by

john.lo7242
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

MSBD 5001

Foundations of Data Analytics


Fall 2024
Tutorial 1: Introduction to Python
and Jupyter Notebook
Cecia Chan
Department of Computer Science and Engineering
The Hong Kong University of
Science and Technology

MSBD5001 Fall 2024 1


Introduction to Python and Jupyter Notebook
• In this tutorial, we will introduce the followings in 3 sections:
• Section 1
• Python
• Anaconda
• Jupyter Notebook
• JupyterLab
• Google Colaboratory
• Section 2
• Markdown, the markup language
• Section 3
• Python Basics

MSBD5001 Fall 2024 2


Section 1
Introduction to Python, Anaconda and
Jupyter Notebook

MSBD5001 Fall 2024 3


Introduction to Python
• Python is a programming language widely used in data science because of
its large number of libraries providing a complete set of tools for analysis
and data manipulation.
• Two releases are distributed in parallel
• Python 2 (version 2.7) and,
• Python 3 (version 3.3 or greater preferred, latest version 3.11).
• IPython is an enhanced command shell for Python.
• Jupyter Notebook (IPython Notebook) is a web browser-based interface to
IPython:
• Good for exploring, sharing, etc.
• JupyterLab is the next-generation web-based user interface for Project
Jupyter.
MSBD5001 Fall 2024 4
Python Versions
• [Link]
• There are many versions of Python started from 1994 to current date

Python Version Released Date


Python 1.0 Jan 1994
Python 2.0 Oct 2000
Python 2.7 Jul 2010
Python 3.0 Dec 2008
Python 3.10 Oct 2021
Python 3.11 Oct 2022
Python 3.12 Oct 2023
MSBD5001 Fall 2024 5
Python Versions
• The Python team has been maintaining both Python 2 and Python 3
since 2006.
• As of January 1, 2020, Python has officially ended the support for Python 2.
• Python 2 and Python 3 are incompatible.
• The latest version is Python 3.12.
• To check the version of Python installed in your computer, you can
write the following code

import sys
print([Link])
MSBD5001 Fall 2024 6
Python, Anaconda and Jupyter Notebook
• Python is required for installing Jupyter Notebook
• Anaconda is recommended to install Python and Jupyter Notebook

MSBD5001 Fall 2024 7


Anaconda
• It is a free distribution of Python packages.
• It supports Windows, Mac & Linux.
• Installation by downloading the corresponding installer:
• [Link]
• It conveniently installs Python, the Jupyter Notebook, and other
commonly used packages for scientic computing and data science.
• E.g. Numpy, SciPy, Scikit-Learn, Pandas, Matplotlib, NLTK, Seaborn, Jupyter
Notebook, JupyterLab, etc.
• It contains conda and Anaconda Navigator.

MSBD5001 Fall 2024 8


Anaconda Navigator
• Anaconda Navigator
• a desktop graphical user interface that allows you to launch applications and
easily manage conda packages, environments, and channels without using
command-line commands.

MSBD5001 Fall 2024 9


Anaconda Navigator

MSBD5001 Fall 2024 10


Conda
• Conda is an open source package management system and environment
management system included in Anaconda and Miniconda.
• For more reference: [Link]
• For use in command line interface such as Anaconda Prompt on Windows
and terminal on macOS and Linux.
• Starting conda
• Windows: From the Start menu, search for and open "Anaconda Prompt".
• Mac: Open Launchpad, then click the terminal icon.
• Linux: Open a terminal window.
• You can find a summary of the most important commands here:
• [Link]

MSBD5001 Fall 2024 11


Multiple Development Environments
• Very often we will need to work on different data science projects
using different libraries. It may become difficult to manage all libraries
in one single development environment.
• Solution: Multiple development environments

MSBD5001 Fall 2024 12


Managing multiple environments with
Anaconda Navigator

To
activate/deactivate
an environment:

To create an
environment:

MSBD5001 Fall 2024 13


Managing multiple environments in Anaconda
using conda
• In “Anaconda Prompt”:
• to create an environment based on Python 3.11 conda create -n py311 python=3.11

• to active the environment: conda activate py311


• you can check the installed Python version by:
python --version

• to deactivate the environment: conda deactivate py311

• to list all the environments: conda env list

• to remove the environment:


conda env remove -n py311
MSBD5001 Fall 2024 14
Jupyter Notebook
• Project Jupyter
• a project with goals to develop free software, open standards and web
services for interactive computing across all programming languages
• [Link]
• The Jupyter Notebook is the web application for creating and sharing
computational documents.
• A jupyter notebook document contains an ordered list of input/output cells
which can contain code, text, mathematics, plots and rich media.
• JupyterLab is the latest web-based interactive development
environment for notebooks, code, and data with more flexibility and
modular design.

MSBD5001 Fall 2024 15


Jupyter Notebook: The Classic Notebook
Interface
• Launching Jupyter Notebook App by
1. clicking the Jupyter Notebook icon

2. typing in the terminal (Anaconda Prompt):


jupyter notebook
• if necessary, you can install Jupyter Notebook by:
• conda install -c conda-forge jupyter Or pip install jupyter

• Jupyter Notebook allows editing and running notebook documents via a web
browser.
• It has a “Dashboard” (Notebook Dashboard)
MSBD5001 Fall 2024 16
Notebook Dashboard
• The Dashboard has a control panel which
• Shows local files
• Opens notebook documents
• Shuts down their kernels

MSBD5001 Fall 2024 17


Creating a New Notebook Document
• Method 1
• From the dashboard:
• Press the New button on the right-hand side and select the corresponding
python version.

MSBD5001 Fall 2024 18


Creating a New Notebook Document
• Method 2
• Within and active notebook, in the menubar, select File, then New:

MSBD5001 Fall 2024 19


Creating a New Notebook Document
• Name or rename the document
• Clicking on the title or File → Rename ...

MSBD5001 Fall 2024 20


Launching a Notebook Document
• To open an existing notebook, in the Dashboard, navigate to the
appropriate folder
• double click the notebook on the Dashboard, or
• check the notebook on the Dashboard and then click "View"

MSBD5001 Fall 2024 21


Closing a Notebook Document
• To close a notebook
• a notebook’s kernel is started
automatically when a notebook is
opened
• closing the browser tab will not shut
down the kernel
• to shut down, click on menu:
File → Close and Halt
• or, select the notebook and click
"Shutdown" on the Dashboard

MSBD5001 Fall 2024 22


Shutting Down the Jupyter Notebook App
• To shut down the Jupyter Notebook App
• close the associated terminal
• Note: closing the browser (or the tab) will not close it
• click the "Quit" button on the top-right corner of the Dashboard

MSBD5001 Fall 2024 23


Downloading a Notebook
• You can download the notebook as
the following formats:
• Notebook file: .ipynb
• Python script: .py
• Rich output removed
• Markdown cells as comments
• etc.

MSBD5001 Fall 2024 24


JupyterLab
• Launching JupyterLab by
1. clicking the JupyterLab icon

2. typing in the terminal (Anaconda Prompt):


jupyter lab
• if necessary, you can install JupyterLab by:

conda install -c conda-forge jupyterlab pip install jupyterlab

MSBD5001 Fall 2024 25


The JupyterLab Interface
• Menu bar
• Left sidebar
• Main work area

MSBD5001 Fall 2024 26


The JupyterLab Interface
• Left sidebar contains
• A file browser

• The table of contents

• A list of running kernels and terminals

• The extension manager

MSBD5001 Fall 2024 27


The JupyterLab Interface
• Right sidebar contains
• The property inspector when
being active in a notebook
• The debugger

MSBD5001 Fall 2024 28


The JupyterLab Interface – Main Work Area
• It contains tabs of
documents and
activities.
• Tabs can be resized or
subdivided by dragging
the tabs.

MSBD5001 Fall 2024 29


Google Colaboratory
• [Link]
[Link]
• It is a research tool by
Google for machine
learning education and
research.
• It is a Jupyter notebook
environment that
requires no setup to
use.

MSBD5001 Fall 2024 30


Google Colaboratory
• It allows us to write and execute
Python code as Jupyter
Notebooks in our browser.
• It runs on Google’s cloud servers.
• The notebooks are saved in our
Google Drive.
• To use Colab:
• You will need to:
1. Have a Google Account
2. Use the Google Drive
3. Access Colab

MSBD5001 Fall 2024 31


Structure of a Notebook Document
• A sequence of cells.
• Three types of cells:
• Code cells
• Markdown cells
• Raw cells

MSBD5001 Fall 2024 32


Structure of a Notebook Document
• To add a cell
• from the menu, click “Insert”, and select either “Insert Cell Above” or “Insert
Cell Below”.

• To edit a cell
• Double click the cell

• To execute a cell, either


• press the shortcut key Shift+Enter
• clicking the “Play” button in the toolbar
• clicking Cell → Run... in the menu bar

MSBD5001 Fall 2024 33


Structure of a Notebook Document –
Code Cells
• Edit or write new code
• With syntax highlighting
• Results are displayed as output in the notebook

MSBD5001 Fall 2024 34


Structure of a Notebook Document –
Markdown Cells
• Adding descriptive texts
• Markdown Language to do text markup, e.g.
italics, bold, lists, etc.
• HTML code
• Mathematics using standard LaTeX notations: $ ...
$, $$ ... $$, \begin{equation} ... \end{equation},
\begin{align} ... \end{align}, etc.

MSBD5001 Fall 2024 35


Structure of a Notebook Document –
Raw Cells
• A place to write output directly
• Not evaluated by the notebook, i.e. unmodified

MSBD5001 Fall 2024 36


Section 2
Markdown, the Markup Language

MSBD5001 Fall 2024 37


Markdown, the Markup Language
• In this section, we will introduce Markdown, the markup language
which we can use in Jupyter notebooks to add formatted
descriptions.
“Markdown is a text-to-HTML conversion tool for web writers.
Markdown allows you to write using an easy-to-read, easy-to-
write plain text format, then convert it to structurally valid
XHTML (or HTML).”
-- [Link]

MSBD5001 Fall 2024 38


Using Markdown in Jupyter Notebook
• You can use Markdown to format the descriptive text in Jupyter
Notebook in the Markdown cells.

• To render the output, press the run button in the tool bar.

MSBD5001 Fall 2024 39


Using Markdown
• There are online Markdown editors that you can try using
Markdown.
• Dillinger is one of the online Markdown editors.
• Just open the site and start typing in the left pane. A preview of the rendered document
appears in the right pane.

MSBD5001 Fall 2024 40


Markdown Basics – Headings
• Headings can be added by starting with one or multiple #, followed by
a space, then the heading text. There are 6 heading levels, or
examples:
Markdown HTML Equivalent
# Heading1 <h1>Heading1</h1>
## Heading2 <h2>Heading2</h2>
### Heading3 <h3>Heading3</h3>
#### Heading4 <h4>Heading4</h4>
##### Heading5 <h5>Heading5</h5>
###### Heading6 <h6>Heading6</h6>

MSBD5001 Fall 2024 41


Headings

Markdown in Jupyter Notebook Rendered Output

MSBD5001 Fall 2024 42


Ordered List
• For each item, add the number plus . and a space
Markdown Equivalent HTML
1. item1 <ol>
2. item2
1. item2.1 <li>item1</li>
2. item2.2 <li>item2
3. item3
<ol>
<li>item2.1</li>
<li>item2.1</li>
</ol>
</li>
<li>item3</li>
</ol>

MSBD5001 Fall 2024 43


Ordered List

Markdown in Jupyter Notebook Rendered Output

MSBD5001 Fall 2024 44


Unordered List
• Unordered lists use asterisks (*), pluses (+) and hyphens (-) as list markers.
• For each item, add either the asterisk (*), plus (+) or hyphen (-), and a space
Markdown Equivalent HTML
- item1 <ul>
- item2 <li>item1</li>
- item2.1 <li>item2
- item2.2 <ul>
- item3 <li>item2.1</li>
<li>item2.1</li>
</ul>
</li>
<li>item3</li>
</ul>

MSBD5001 Fall 2024 45


Unordered List

Markdown in Jupyter Notebook Rendered Output

MSBD5001 Fall 2024 46


Text Formatting Style – Line Break
• The rendered output will not be shown in separate lines by just using
an enter at the end of the line.

• Line breaks can be added using two or more spaces at the end of the
line. (Note: Equivalent HTML tag: <br />.)

MSBD5001 Fall 2024 47


Text Formatting Style – Italic & Bold
• Italic - Make the text italic by adding a pair of *s around the text.
Bold - Make the text bold by adding a pair of **s around the text.
Markdown Equivalent HTML
* italics * <em>italics</em>
** bold ** <strong>bold</strong>

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 48


Text Formatting Style – Strikethrough
• Wrap the text with tilde symbols (~~~).
Markdown Equivalent HTML
~~~deleted~~~ <del>deleted</del>

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 49


Text Formatting Style – Blockquote
• Preceding the quote by the symbol >.
Markdown Equivalent HTML
> This is a blockquote. <blockquote>This is a blockquote.</ blockquote>

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 50


Text Formatting Style – Blockquote
• Markdown in Cell and the Rendered Output of a nested
blockquote:

MSBD5001 Fall 2024 51


Text Formatting Style – Paragraphs
• Paragraphs are separated by one or more blank lines.
Markdown Equivalent HTML
This is a paragraph. <p>This is a paragraph.
This is the second sentence of the 1st This is the second sentence of the 1st
paragraph. paragraph.</p>

This is another paragraph. <p>This is another paragraph.</p>

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 52


Horizontal Lines
• Horizontal lines can be created by using 3 hyphen (-), underscore (_) or asterisk
(*) symbols.
Markdown Equivalent HTML
--- <hr />
___ <hr />
*** <hr />

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 53


Hyperlinks
• URLs will be automatically recognised.
Or wrap the link text with square brackets ([]) and the link in round brackets (()).
Markdown Equivalent HTML
[Link] <a href="[Link]

[HKUST]([Link] <a href="[Link]

• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 54


Code
• Inline code can be wrapped by using backquotes (`), while code segment can be
wrapped by 3 backquotes (```)
• Syntax highlighting can be enabled for code segment by adding the language
name after the starting 3 backquotes.
Markdown Equivalent HTML
To print a string in python: To print a string in python:
`print("Hello world!")` <code>print("Hello world!")</code>

Here is a function: Here is a function:


``` <pre>
def fun(): <code>
print("Hello world!") def fun():
``` print("Hello world!")
</code>
</pre>
MSBD5001 Fall 2024 55
• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 56


Table
• A table can be formatted using
pipe symbol (|) and hyphen symbol (-).
Markdown Equivalent HTML
|Header1|Header2|Header3| <table>
|-------|-------|-------| <thead>
|cell11 |cell12 |cell13 | <th>Header1</th><th>Header2</th><th>Header3</th>
|cell21 |cell22 |cell23 | </thead>
|cell31 |cell32 |cell33 | <tr><td>cell11</td><td>cell12</td><td>cell13</td></tr>
<tr><td>cell21</td><td>cell22</td><td>cell23</td></tr>
<tr><td>cell31</td><td>cell32</td><td>cell33</td></tr>
</table>

MSBD5001 Fall 2024 57


Table
• Markdown in Cell and the Rendered Output:

MSBD5001 Fall 2024 58


Graphics
• To attach an image in the markdown cell, you can just drag and drop
the image into the cell (the image should be in the same folder as the
notebook),
• Or by using the following syntax (filename, the corresponding filepath
or link):
Markdown Equivalent HTML
![Picture Title](attachment:[Link]) <img src="[Link]">Picture Title</img>

MSBD5001 Fall 2024 59


Math Equation
• Latex can be used to typeset formulas in a notebook.
• In-line Math
• Using the $ symbol within a Markdown cell. For example,

MSBD5001 Fall 2024 60


Math Equation
• Math Block
• Using the $$ symbol within a Markdown cell. For example,

MSBD5001 Fall 2024 61


Colab Markdown
• There are some differences between the Markdown used by Colab
(Colab Markdown) and the Markdown used by Jupyter.
• Colab uses [Link] and so is similar but not quite identical to the
Markdown used by Jupyter.
• Colab supports (MathJax) LATEX equations like Jupyter, but does not allow
HTML tags in the Markdown.
• Colab Markdown Guide:
[Link]

MSBD5001 Fall 2024 62


Section 3
Python Basics
Part 1 – Python Basics

MSBD5001 Fall 2024 63


Python Basics
• In this section, we will
introduce Python Basics
using a Jupyter
Notebook
• Download the Notebook
file:
tut1_PythonBasics.ipynb
• Launch the Jupyter
Notebook

MSBD5001 Fall 2024 64


Python – Versions
• Python is a high-level, dynamically typed programming language.
• There are two versions of Python, 2.7 and 3.,7 supported currently.
• Python 3 is not backward-compatible with Python 2.
• Code written under version 2.7 may not work under version 3.7 and
vice versa.
• We will be using Python 3 in this course
• To check the version of Python installed in your computer, you can
write the following code
import sys
print([Link])
MSBD5001 Fall 2024 65
Python – Syntax
• Python has no mandatory statement termination characters.
• A statement is usually just a line of code. Only extra blanks and tabs
are ignored.
• But there are two ways of having a multi-line statement:
1. Explicit line continuation
• using the line continuation character (\).
2. Implicit line continuation
• splitting a statement with parentheses ( ), brackets [ ] and braces { } across
lines.

MSBD5001 Fall 2024 66


Python – Syntax
• Blocks are specified by indentation.
• The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.
• Statements that expect an indentation level end in a colon (:).
• Comments
• One-line comment starting with the pound(#) sign.
• Multi-line comment
• multi-line strings, delimited by triple quote (""").

MSBD5001 Fall 2024 67


Variables
• A variable is a named piece of memory that can store a value.
• Assignment statement:
• stores a value into a variable.
x = 100

• Naming rule
• Variables’ names must start with a letter or an underscore, such as:
• _underscore
• underscore_
• The remainder of the variable name may consist of letters, numbers and underscores.
• password1
• n00b
• un_der_scores
• Names are case sensitive.
• case_sensitive, CASE_SENSITIVE, and Case_Sensitive are different variables

MSBD5001 Fall 2024 68


Basic Data Types
Name Type Description Mutable or
Immutable?
Integers int Whole numbers, e.g. 2, 10, 123, -101 Immutable
Floating point float Numbers with a decimal point, e.g. 3.1457, 0.34 Immutable
numbers
Booleans bool Logical value: True or False Immutable

Strings str Ordered sequence of characters, e.g. "hello", "Python" Immutable

• We can use type() to get the type of the data.


print(type(1))
print(type(1.2)) <class 'int'>
print(type(False)) <class 'float'>
x1 = 100 <class 'bool'>
print(type(x1)) <class 'int'>
x2 = "hello" <class 'str'>
print(type(x2))
MSBD5001 Fall 2024 69
Basic Data Types
• To convert the data type from one to another.
• int(), float(), str()

num = 10
print(type(num))
print(type(str(num)))
text = "123.5"
print(type(text))
print(type(float(text))) <class 'int’>
<class 'str'>
<class 'str'>
<class 'float'>

MSBD5001 Fall 2024 70


Operators and Expressions
• Expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
• Arithmetic operators • Assignment operators
Operator Description
Operator Description
+ Addition
= Assignment
- Subtraction
+= Addition assignment
* Multiplication
-= Subtraction assignment
/ Division
// Integer Division *= Multiplication assignment

% Modulus (Remainder) /= Division assignment


** Power
MSBD5001 Fall 2024 71
Operators and Expressions
• Relational operators • Comparison Operators
Operator Description Operator Description
and And > Larger than
or Or >= Larger than or equal to
not Not < Smaller than
<= Smaller than or equal to
== Equal to
!= Not equal to

MSBD5001 Fall 2024 72


Operators and Expressions
• Walrus Operator :=
• Assignment Expression Operator
• Introduced since Python 3.8.
• Used in constructing assignment expressions to assign and return variables in
the middle of the expressions.

print (x := True)

MSBD5001 Fall 2024 73


If Statement
• Syntax:
if (<bool-expr>) : if (<bool-expr>) :
<stmt(s)> <stmt(s)>
elif (<bool-expr>) :
<stmt(s)>

if (<bool-expr>) :
<stmt(s)> if (<bool-expr>) :
else : <stmt(s)>
<stmt(s)> elif (<bool-expr>) :
<stmt(s)>
else : <stmt(s)>

MSBD5001 Fall 2024 74


Loops
• while loop • for loop
• Syntax: • Syntax:

while (<bool-expr>) : for <item> in <a list of items> :


<stmt(s)> <stmt(s)>

MSBD5001 Fall 2024 75


break and continue
• break and continue are loop control statements executed inside a loop.
• The continue statement causes the loop to skip its current execution at some
point and move on to the next iteration.
• The break statement terminates the loop immediately and transfers execution to
the new statement after the loop.

MSBD5001 Fall 2024 76


Functions
• Functions are declared with the def keyword.
• A Python function need not specify the parameter types and return types.
• Syntax:
def <function-name>(<arguments>):
<stmt(s)>

MSBD5001 Fall 2024 77


Section 3
Python Basics
Part 2 – More about Python Basics Data Types

MSBD5001 Fall 2024 78


More about Basic Data Types – Strings
• Strings can be defined by use of single ('), double (") or triple ("') quotes.
• Strings enclosed in triple quotes ("') can span over multiple lines.
• Creating a string:
greeting = 'Hello'

• Accessing a string element with index:


print (greeting[0]) # Return character at index 0
print (greeting[1]) # Return character at index 1
print (greeting[-1]) # Return the last character

• Note: string is immutable:


greeting[1] = 'x' # syntax error
MSBD5001 Fall 2024 79
String Methods
• There are many methods for manipulating string:
h = 'hello'
w = "world"
hw = h + '\t' + w # string concatenation
print(hw)
print("# chars in hw=", len(hw)) # len() gives the string length
print(h*3) # duplicate the string 3 times
print([Link]()) # Capitalize the string in h, prints "Hello"
print([Link]()) # Cover to uppercase, prints "HELLO"
print([Link]("ll")) # Return the smallest index where the given substring is found
print([Link]()) # Return True if all characters are digits
print([Link]()) # Return True if all characters are alphabets
print([Link]("rl", "o")) # Replace all occurrences "rl" with "o"

• For more methods:


• [Link]

MSBD5001 Fall 2024 80


String Literals
• We can add a prefix in front of string literals:
Prefix Meaning Example
u or U Unicode string, which is the default in Python 3 u_string = u"Hi"
Byte string, which is machine-readable and need decoding b_string = b'\x48\x69'
b or B
to become readable to human.
Raw string, which the character following a backslash is
r or R included in the string without change (i.e. not treated as an r"hello\nworld"
escape character)
Formatted string, which may contain expressions with f"a + b = {a+b}"
f or F
braces

• Raw strings str = r'\n is a newline character by default'


# Raw strings can be defined by adding r to the string
print (str)

MSBD5001 Fall 2024 81


Unicode and Byte Strings
u_string = u"Hi"
print(u_string) # unicode string
print(u_string.encode('utf-8')) # convert unicode string to byte string
print(type(u_string))

b_string = b'\x48\x69' # byte string


print(b_string.decode('utf-8')) # convert byte string to unicode string
print(type(b_string))

u_string = u"\U0001f600"
print(u_string)
print(u_string.encode('utf-8'))

MSBD5001 Fall 2024 82


String Formatting
• Other types of values may be embedded in string using %
• For example
• %d is used to embed integer
• %s is used to embed a string
• %f is used to embed a float
• An example to use the above:
>>> num = 10
>>> print("The value stored in num is %d." % num)
The value stored in num is 10.

• Escape characters: \t for tab, \n for Enter

MSBD5001 Fall 2024 83


Formatted Strings
• f-strings
• It allows us to include the value of expressions inside a string by
• prefixing the string with ‘f’ or ‘F’ and a = 1
• wrapped by a braces, e.g. {expression} b = 2
print( f"a + b = {a+b}" )

• We can add an optional format specifier after the expression to specify how
the value is formatted
• For example,
• to rounds a floating-point number to three places after the decimal, and
• to print the value with a minimum width of 10
num = 1/3
print(f'The num is approximately {num:10.3f}.')

MSBD5001 Fall 2024 84


Formatted Strings
• Alignment options of the formatted string
• The following options can be included in the formatted string to specify the
alignment of the expression.
Option Description
< Left alignment (default)
> Right alignment
^ Center alignment

name = "Python"
print(f"{name:>30}")
print(f"{name:<30}")
print(f"{name:^30}")

MSBD5001 Fall 2024 85


Section 3
Python Basics
Part 3 – Python Basics Data Structures

MSBD5001 Fall 2024 86


Basic Data Structures
Mutable or
Name Type Description
Immutable?
Lists list Ordered sequence of objects, e.g. [1, 5, 7], [10, 2.3, "hello"] Mutable
Tuples tup Ordered immutable sequence of objects, e.g. ("a", "a", "b") Immutable
Sets set Unordered collection of unique items, e.g. {1, 5, 7} Mutable
Dictionaries dict Unordered key-value pairs, e.g. {"Ann":12, "Bob":5} Mutable

• For more details: [Link]


• We can use type() to get the type of the data structures.
x3 = ["a", "b"]
print(type(x3))
x4 = {"a":1, "b":2} <class 'list’>
print(type(x4)) <class 'dict'>

MSBD5001 Fall 2024 87


Lists
• A list is defined by writing a list of comma separated values in a square brackets.
• Lists might contain items of different types, but usually the items all have the same type.
• We can change the items in the list, i.e. mutable.
list1 = [] # empty list
print (list1) # print []
list2 = [3, 2, 4]
print(list2) # print [3, 2, 4]
[Link](3) # add an item to the end of the list
print(list2) # print [3, 2, 4, 3]
list3 = list2 + [6, 1] # concatenate 2 lists
list3 += [11, 8] # add a list to the end
print(list3) # print [3, 2, 4, 3, 6, 1, 11, 8]
[Link](3) # remove the 1st occurrence of the item
print(list3) # print [2, 4, 3, 6, 1, 11, 8]
print(list3[2]) # Get the item with index 2 (3rd item); print 3
print(list3[-1]) # Negative index counts from the end; print 8

• More about lists: [Link]


MSBD5001 Fall 2024 88
Slicing
• To access sublists
num_list = [3, 2, 16, 8, 30, 22]
print ("Slicing examples:")
print (num_list[2:4]) # Return a new list from index 2 to 4 (exclusive)
print (num_list[2:]) # Return a new list from index 2 to the end
print (num_list[:2]) # Return from the start to index 2 (exclusive)
print (num_list[:]) # Return the whole list
print (num_list[:-1]) # Slice indices can be negative

print ("Slicing with step:")


print (num_list[::2]) # Return every 2nd item
print (num_list[::-1]) # Return a reversed list

print ("More examples:")


num_list[2:4] = [0, 0] # Assign a new sublist to a slice
print (num_list) # Prints "[3, 2, 0, 0, 30, 22]"

MSBD5001 Fall 2024 89


Loops and Sequences
• We can loop over the items in a lists.

nums = [0, 1, 8, 9, 4]
for each_num in nums:
print(each_num, end=' ')
print()

for each_index in range(len(nums)):


print(nums[each_index], end=' ')
print()

MSBD5001 Fall 2024 90


in and not in
• in and not in are operators to tell us whether a value is present or
absent in a collection of values.
nums = [0, 1, 8, 9, 4]
print(5 in nums)
print(5 not in nums)
print(8 in nums)
print(8 not in nums)
False
True
True
False

MSBD5001 Fall 2024 91


Nested Lists
• A two-dimensional list is like a list of lists.
board = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]
[Link](['i', 'j', 'k', 'l'])

print(board) # board has 3 lists


print(board[0]) # print the 1st list (index 0), i.e. ['a','b','c','d']
print(board[0][0]) # print the 1st item (index 0) in the 1st list (index 0)
# i.e. 'a'
print(board[2]) # print the 3rd list (index 2), i.e. ['i','j','k','l']
print(board[2][3]) # print the 4th item in the 3rd list, i.e. 'l'

• Using nested loops to get each of the item in a two-dimensional lists.


for row in board: for i in range(len(board)):
for each_item in row: for j in range(len(board[i])):
print(each_item, end=' ') a b c d print(board[i][j], end=' ')
print() e f g h print()
i j k l
MSBD5001 Fall 2024 92
List Comprehensions
• List comprehensions provide a concise way to create lists.
• A list comprehension consists of brackets containing an expression followed by a for
clause, then zero or more for or if clauses.
• The result will be a new list.
• For example, instead of using a for loop to generate a list of squares, we can also
generate a list of squares using list comprehension:
nums = [0, 1, 2, 3] nums = [0, 1, 2, 3]
squares = [] squares = [x**2 for x in nums]
for x in nums: print (squares)
[Link](x**2)
print (squares)

MSBD5001 Fall 2024 93


List Comprehensions
• A list comprehension can also contain if clauses after the expression and for
clause.
• The following list comprehension creates a list of odd numbers by checking that
the number is not divisible by 2.

nums = [0, 1, 2, 3]
squares = [x**2 for x in nums if x%2]
print(squares)

• A list comprehension can consist of multiple for clauses.


num_list1 = [[1, 2, -3], [4, -5, 3], [9, 8, 11]]
# flatten a list using list comprehension with 2 for
numbers = [num for row in num_list1 for num in row]
print(numbers)

MSBD5001 Fall 2024 94


[Link]() vs [Link]() vs [Link]()
• [Link](x)
• Add an item to the end of the list. An iterable is an object that can be used as a
sequence. It can be looped over.
• [Link](iterable)
• Extend the list by appending all the items from the iterable.
• [Link](i, x)
• Insert an item (x) at a given position (i).
• i is the index of the element before which to insert.

Which one is more efficient?

MSBD5001 Fall 2024 95


[Link]() vs [Link]()
• [Link](x)
• Remove the first item from the list whose value is equal to x.
• [Link]([i])
• Remove the item at the given position in the list, and return it.
• If no index is specified, [Link]() removes and returns the last item in the list.

MSBD5001 Fall 2024 96


Operation Result
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
appends x to the end of the sequence (same
[Link](x)
as s[len(s):len(s)] = [x])
[Link]() removes all items from s (same as del s[:])
[Link]() creates a shallow copy of s (same as s[:])
extends s with the contents of t (for the most part the same
[Link](t) or s += t
as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
[Link](i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
[Link]() or [Link](i) retrieves the item at i and also removes it from s
[Link](x) removes the first item from s where s[i] is equal to x
[Link]() reverses the items of s in place
MSBD5001 Fall 2024 97
Tuples
• A tuple is represented by a number of values separated by commas.
• Tuples are immutable and output is surrounded by parentheses.
• Faster in processing than lists.
tuple_example = 0, 1, 4, 9, 16, 25
print (tuple_example) # Output would be enclosed in parenthesis

# Parenthesis will be necessary if the tuple is part of a larger expression


tuple_example2 = (0, 2, 4), (1, 3, 5)
print (tuple_example2)

print (tuple_example[2]) # Indexing returns the items


tuple_example[2] = 6 # Tuples are immutable and hence this is an error

MSBD5001 Fall 2024 98


Sets
• A set is an unordered collection of distinct elements.
• Sets do not record element position or order of insertion.
• Sets do not support indexing, slicing, or other sequence-like behavior.

fruits = {'Orange', 'Apple'}


print (fruits)

print('Apple' in fruits) # Check if an element is in a set


print('Banana' in fruits)
[Link]('Banana') # Add an element to a set
print('Banana' in fruits)
print (len(fruits)) # Get the number of elements in a set
[Link]('Apple') # Add an element that is already in the set does nothing
print (fruits)
[Link]('Apple') # Remove an element from the set
print (fruits)

MSBD5001 Fall 2024 99


Sets
• Create a set using set().
items = set() # Create an empyy set
[Link]("Coke")
[Link]("Potato chips")
print (items)

• Set operations:
set1 = set("banana") # A set of unique characters
set2 = set("apple")
print (set1)
print (set2)
print ("Set operations:")
print (set1 - set2) # characters in set1 but not set2
print (set1 | set2) # characters in set1 or set2
print (set1 & set2) # characters in both set1 and set2
print (set1 ^ set2) # characters in set1 or set2 but not both

MSBD5001 Fall 2024 100


Set Comprehension
• The syntax of the Set comprehension is similar to the List comprehension,
except that braces are used instead of square brackets.
list1 = [ 1, 2, 3, 3, 2, 5, 7, 0 ]
set1 = set()
# create a set using set comprehension
set1 = {x for x in list1}
print(set1)

MSBD5001 Fall 2024 101


Dictionaries
• Dictionary is an unordered set of key: value pairs, with the requirement that the
keys are unique (within one dictionary).
• A pair of braces creates an empty dictionary: {}.
extensions = {'CSE': 1234, 'DSCT': 7444, 'ECE': 7036}
print (extensions)

extensions['CSE'] = 7000 # Modify the value for the key 'CSE'


print (extensions['CSE']) # Get the value of the key 'CSE'
extensions['MAE'] = 8654 # Add a key-value pair
print (extensions)

print ([Link]()) # Get the keys only


print ([Link]()) # Get the values only
print ([Link]()) # Get the key-value pairs

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

MSBD5001 Fall 2024 102


Dictionary Comprehensions
• There are two expressions with a colon (:) between them for the key and
corresponding value before the for.
item2quantity = {"Chocolate bar":123, "Marshmallows":213, "Gummy":101}

# create a dictionary with dict comprehension


dict1 = {n:q-1 for n, q in [Link]()}

print(dict1)

MSBD5001 Fall 2024 103


Shallow and Deep Copy Operations
• Assignment statements in Python do not copy objects, they create bindings.
list1 = [1, 2, 3]
list2 = list1 # list2 is bound to list1
list2[0] += 10 # changing list2 is the same as change list1
print(list1)
[11, 2, 3]
• Shallow Copy:
• Using copy() method of the data structure or [Link]() from the copy module

list1 = [1, 2, 3] import copy


list3 = [Link]() list1 = [1, 2, 3]
list3[0] += 10 list4 = [Link](list1)
print(list1) list4[0] += 10
print(list4)

MSBD5001 Fall 2024 104


Shallow and Deep Copy Operations
• Problem of shallow copy:
import copy
list2d1 = [[1, 2, 3], [4, 5, 6]]
list1 = [1, 2, 3]
list2d2 = [Link]()
list4 = [Link](list1)
list2d2[0][0] += 10
list4[0] += 10
print(list2d1)
print(list4)
[[11, 2, 3], [4, 5, 6]]
• Deep copy:
• using [Link]():
import copy
list2d1 = [[1, 2, 3], [4, 5, 6]]
list2d3 = [Link](list2d1)
list2d3[0][0] += 10
print(list2d1) [[1, 2, 3], [4, 5, 6]]
• More about copy: [Link]

MSBD5001 Fall 2024 105


Parallel Iteration
• zip() is a built-in function.
• It iterates over several iterables in parallel, producing tuples with an item from
each one.

strlist = ["Ann", "Bob", "Candy"]


numlist = [100, 86, 92]
print(zip(strlist, numlist))

for item in zip(strlist, numlist): <zip object at 0x0000019FC5195680>


print(item) ('Ann', 100)
('Bob', 86)
('Candy', 92)

• For more about zip(): [Link]


MSBD5001 Fall 2024 106
Section 3
Python Basics
Part 4 – More on Functions

MSBD5001 Fall 2024 107


More on Functions
• A function is a sequence of instructions.
• Function Definition
• def is a python keyword which is to create a function
• It is followed by the name of the function name, and a pair of parentheses, which may or
may not contain a list of input values.
• A colon (:) indicates the end of the function definition
• Function Body
• Contains the sequence of instructions
• The body of the function start at the next line.
• The statements of the function body must be indented.

MSBD5001 Fall 2024 108


More on Functions
• return Statement
• Usually, a function returns something, for example,
• The result of some computations
• A signal about the status of the function
• A new object created by the function
• It is done by using the return keyword, and followed by the output
• The return keyword can also be used to terminate the function early by using the return
keyword only without a value.

import random # using the random module


def get_random_number():
return [Link](1, 100)

print( get_random_number() )
MSBD5001 Fall 2024 109
Parameters and Arguments
• Parameters
• They are the variables specified in the function definition
• They describes what information are needed by the function
• In the following example, x is a parameter. The function takes the value in x,
and then returns the square of the value. def square(x):
result = x**2
return result
• Arguments
• The information that is passed from a function call to a function
• In the above function call, the value 10 is passed to the parameter x
print("The square of 10 is", square(10))

MSBD5001 Fall 2024 110


Local and Global Variables
• Global scope
• The names that you define in this scope are available to all your code.
• Local scope
• The names that you define in this scope are only available or visible to the code within the
scope.
• Variables created inside a function are normally with local scope, while variables created
outside a function are with global scope.
def fun(parameter1):
# parameter1 is a local variable
parameter1 = parameter1 + 30
print("In fun():", var1, parameter1)

var1 = 0 # variable with global scope (global variable)


fun(var1)
print('var1 =', var1)
print('parameter1 = ', parameter1) # cannot access the local variable

MSBD5001 Fall 2024 111


Local and Global Variables
• The global Statement
• If we want to create/use a global variable inside a local scope (e.g. function),
we can add the global statement as the first statement of a function body.
var1 = 0 # variable with global scope (global variable)

def fun():
global var1
var1 = var1 + 10 # modify the global var1
print('In fun(), var1 =', var1) # read the global variable

fun()
print('var1 =', var1)

MSBD5001 Fall 2024 112


Default Values
• We can give a default value to a parameter in a function definition.
• If we pass an argument to a parameter in the function call, the argument value
will be used.
• If we do not pass an argument to a parameter with a default value, the default
value will be used instead.
def add(x, y=1):
return (x + y)

MSBD5001 Fall 2024 113


Positional and Keyword Arguments
• We can pass arguments to a function in different ways
• Positional arguments
• Keyword arguments

MSBD5001 Fall 2024 114


Positional Arguments
• Positional arguments
• When we call a function, the parameters in the function definition take the
information (values) in the order of the arguments in the function call.
def total_amount(product_name, price, quantity):
amount = price * quantity
print('You need to pay $', amount, 'for', quantity, product_name)

total_amount('candy', 5, 10)

• Positional-Only Arguments
• If we do not know how many positional arguments will be passed to the
function, we can add an asterisk (*) before the parameter name.
• It will give us a tuple of arguments.
def get_args(*args):
print("The positional arguments are", args)

get_args("a", "b", 10)


MSBD5001 Fall 2024 115
Keyword Arguments
• Keyword arguments
• A keyword argument is a name-value pair that we pass to a function.
• We specify the value and the parameter to be passed to within the argument.
• The order of the keyword arguments is not important.
• For example, we can also call the total_amount() function by specifying each parameter
def
name:
total_amount(product_name, price, quantity):
amount = price * quantity
print('You need to pay $', amount, 'for', quantity, product_name)
total_amount(price=5, product_name='candy', quantity=10)
• Keyword-Only Arguments
• If we do not know how many keyword arguments will be passed to the function, we can add
2 asterisks (**) before the parameter name.
• It will give us a dictionary of arguments.
def get_kargs(**kargs):
get_kargs(name="Ann", age=20, prog="MSBD")
print("The keyword arguments are", kargs)

MSBD5001 Fall 2024 116


Passing Objects
• We can pass more complex things than simple values to a function, e.g. a list, a
dictionary, etc.
• Passing a dictionary to a function
• If we pass a dictionary to a function, we can modify the dictionary inside the function body.
• The changes are permanent.
• Passing a list to a function
• If we pass a list to a function, we can modify the list inside the function body.
• The changes are permanent.
• The reason is that both list and dictionary are mutable objects.
• Prevent a Function from Modifying a List
• If we want to pass a list to a function without being modified, we can pass a copy of a list to a
function by:
function_name(list_name[:])

MSBD5001 Fall 2024 117


Section 3
Python Basics
Part 5 – Lambda

MSBD5001 Fall 2024 118


Lambda Expressions
• Lambdas are small anonymous functions created by the keyword lambda
• The syntax:
lambda [parameter_list]: expression
• parameter_list is optional
• A normal function:
def func_name([parameter_list]):
return expression
is equivalent to the lambda:
func_name = lambda [parameter_list]: expression

MSBD5001 Fall 2024 119


Lambda Expressions – An Example
f1 = lambda a, b: a+b

• The lambda keyword returns a function object.

print( f1 ) <function <lambda> at 0x00000218A390FAC0>

• To call the lambda expression as function:


print( f1(1, 2) ) 3

MSBD5001 Fall 2024 120


More about Lambda
• Lambda expressions cannot contain statements.
• Lambdas can reference variables from the containing scope:

a = 3
b = 4
print( (lambda: a+b)() )

MSBD5001 Fall 2024 121


Using Lambda with Built-in Functions –
sorted()
• The built-in function sorted() builds a new sorted list from the items in a list
(iterable).
• It can take keyword argument, key, which is a function of one arguments that is
used for comparison during sorting

tuple_list = [ ("Bob", 6), ("Stuart", 4), ("Fred", 18), ("Ann", 20) ]

tuple_list_sorted = sorted(tuple_list)
print(tuple_list_sorted)

tuple_list_sorted = sorted(tuple_list, key=lambda x: x[1])


print(tuple_list_sorted)
[('Ann', 20), ('Bob', 6), ('Fred', 18), ('Stuart', 4)]
[('Stuart', 4), ('Bob', 6), ('Fred', 18), ('Ann', 20)]

MSBD5001 Fall 2024 122


Using Lambda with Built-in Functions –
[Link]()
• Alternatively, we can also use the [Link]() method of a list to sort the list in
place, i.e. the list itself is sorted after the call.

tuple_list.sort()
print(tuple_list)

tuple_list.sort( key=lambda x: x[1] )


print(tuple_list)

• More about [Link]():


[Link]

MSBD5001 Fall 2024 123


Using Lambda with Built-in Functions – filter()
• filter()
• a Python built-in function
• E.g. if we use filter with a list, alist, and a function, fun,
filter(fun, alist), it means: ( item for item in alist if fun(item) )
• Note that it returns an iterator.
alist = [ [Link](1, 100) for _ in range(10) ]
print(alist)

result_list = list( filter( lambda x: (x % 2 == 0), alist ) )


print(result_list)
[33, 32, 13, 4, 91, 60, 4, 43, 76, 28]
<filter object at 0x000001A77E0DE230>
• More about filter(): [32, 4, 60, 4, 76, 28]
[Link]
MSBD5001 Fall 2024 124
Using Lambda with Built-in Functions – map()
• The map() method can be used to apply a function to every item of a list
(iterable).
• Note that it returns an iterator.
num_list1 = [1, 2, 3]
num_list2 = [11, 22, 33]

result = map(lambda x, y: x*y, num_list1, num_list2)


print(result)
print(list(result))
<map object at 0x000001A77E0E2AD0>
[11, 44, 99]

• More about map():


[Link]

MSBD5001 Fall 2024 125


Section 3
Python Basics
Part 6 – Classes

MSBD5001 Fall 2024 126


Classes and Objects
• In object-oriented programming (OOP), we write classes and create
objects based on the classes.
• Classes
• User-defined data types
• For defining the attributes (data members) and behaviours (methods) for
objects of a class
• Objects
• Instances of a class
• Instantiation – making an object from a class
• Created with specifically defined data

MSBD5001 Fall 2024 127


Class Definition
• The definition of a class has the following syntax
class classname(base-classes):
class-body

• classname is an identifier, which follows the naming rules of variables.


• bass-classes is optional, it is a comma-separated list of classes inherits from.
• class-body is where we specify the attributes and behaviors.

MSBD5001 Fall 2024 128


Class Definition – An Example
class Person:
""" a simple example of class definition """
def __init__(self, name, age):
""" initialize the attributes """
[Link] = name
[Link] = age

def printInfo(self):
""" print the attributes """
print(f"{'Name':<10}: {[Link]:>10}\n{'Age':<10}: {[Link]:>10}")

def increaseAge(self, years=1):


""" increase the age attribute """
[Link] += years

MSBD5001 Fall 2024 129


The init_() Method
• A method is a function defined in a class.
• A method always have the first parameter with the name self.
• self refers to the instance (object) that we are calling the method for.
• The __init__() method is a special method called constructor that Python runs
automatically when we make an instance based on a class.

MSBD5001 Fall 2024 130


Instantiation
• Making an Instance from a Class
person1 = Person("Ann", 20)

• Python will call the init() method with the 3 arguments


• pass them to the parameters, name, gender and weight, and
• assign them to the attributes of the object
• Accessing an Attribute or Method of a Class
• Use the following syntax:
object.attribute_name

MSBD5001 Fall 2024 131


Operator Overloading
• Python provides some special methods which will be automatically called when
the objects perform certain operations.
• For example, when we use the addition operator (+), the special method __add__
is automatically invoked.
• This allows us to customize the behavior of a class for some operators by adding
those methods to our class definition.
• Note:
• Follow the convention use of the operations!
• Don’t surprise the users!

MSBD5001 Fall 2024 132


Overloading the Operators
Unary Arithmetic Operators
Unary Operator Function Definition

Binary Arithmetic Operators - __neg__(self)

Binary Function Definition + __pos__(self)


Operator
+ Comparison Operators
__add__(self, other)
Operator Function Definition
- __sub__(self, other)
< __lt__(self, other)
* __mul__(self, other)
> __gt__(self, other)
/ __truediv__(self, other)
<= __le__(self, other)
// __floordiv__(self, other)
>= __ge__(self, other)
% __mod__(self, other)
== __eq__(self, other)
** __pow__(self, other)
!= __ne__(self, other)

MSBD5001 Fall 2024 133


Overloading str() and bool()
• Python also allows us to customize many other operations.
• Here are some more examples:
• __str__(self)
• For representing an object as string
• For example, the function call str(x) automatically calls x.__str__(), which returns a string
representation of the object.
• __bool__(self)
• For evaluating an object as true or false
• For example, the function call bool(x) automatically calls x.__bool__(), which will
return True or False.

MSBD5001 Fall 2024 134


Operator Overloading – An Example
class Time: def __gt__(self, other):
def __init__(self, hours, mins, secs): if [Link] > [Link]:
[Link] = hours return True
[Link] = mins elif [Link] == [Link]:
[Link] = secs if [Link] > [Link]:
return True
def __add__(self, other): elif [Link] == [Link]:
carry = 0 if [Link] > [Link]:
total_mins = 0 return True
total_hours = 0 return False
total_secs = [Link] + [Link]
if total_secs >= 60: def __str__(self):
carry = total_secs // 60 return str([Link])+":“
total_secs = total_secs % 60 +str([Link])+":"+str([Link])
else:
carry = 0 def __bool__(self):
total_mins = [Link] + [Link] + carry if [Link] or [Link] or [Link]:
if total_mins >= 60: return True
carry = total_mins // 60 return False
total_mins = total_mins % 60
else:
carry = 0
total_hours = [Link] + [Link] + carry
return Time(total_hours, total_mins, total_secs)
MSBD5001 Fall 2024 135
Operator # create the Time objects
start_time = Time(1, 59, 40)
duration = Time(0, 2, 30)
Overloading – end_time = start_time + duration

An Example # print the string representations


print(str(start_time))
print(str(end_time))

# comparison operations
print(end_time > start_time)
print(start_time > end_time)
print(start_time > start_time)

# bool operation
zero_time = Time(0, 0, 0)
print("bool(zero_time) =",bool(zero_time))
print("bool(duration) =",bool(duration))
if duration:
print("some time passed.")
else:
print("no time passed.")

MSBD5001 Fall 2024 136


Inheritance
• In OOP, inheritance allows classes to reuse code from other classes.
• The child (derived) class inherits the members (attributes and methods) of
the parent (base) class.
• The code of the base class can be reused in the derived class.
• New attributes and methods can be added to the derived class.
• We can also override a method from the base class if the method is not good
enough for the derived class.
• This is done by defining a method with the same name in the derived class.

MSBD5001 Fall 2024 137


Inheritance
• For example, the Student class inherits from the Person class.
class Student(Person):

def __init__(self, name, age, sid, program):


# class the __init__() method of the base class Person
super().__init__(name, age)
[Link] = sid
[Link] = program

def printInfo(self):
super().printInfo()
print(f"{'ID':<10}: {[Link]:>10}")
print(f"{'Program':<10}: {[Link]:>10}")

• super() is a special function that allows us to call a method from the parent
(base) class.

MSBD5001 Fall 2024 138


Overriding Methods from the Parent Class
• Besides adding new methods to the derived class,
• We can override a method from the base class if the method is not good enough
for the derived class.
• This is done by defining a method with the same name in the derived class.

MSBD5001 Fall 2024 139


A Note about Private
• In other OOP languages, such as C++, there is the concept of private attributes/methods and
public attributes/methods
• Private – things that should not be accessed outside the object
• Protected - things that cannot not be accessed outside the object except the derived objects
• Public – things that can be accessed outside the object
• Python does not enforce this concept.
• But there is a convention adopted by most Python code:
• An attribute or method name prefixed with an underscore (_) should be regarded as protected
• An attribute or method name prefixed with two underscores (__) should be regarded as private
• Name mangling
• Python will replace any names in a class with two leading underscores, e.g. __membername, by
_classname__membername.
• This help to avoid name clashes of names with names defined by subclasses.

MSBD5001 Fall 2024 140


References
• Python: [Link]
• Anaconda: [Link]
• Conda cheat sheet: [Link]
guide/[Link]
• Jupyter: [Link]
• Jupyter Notebook Documentation: [Link]
• JupyterLab Documentation: [Link]
• Jupyter Team. (2015). Jupyter Notebook: Notebook Examples: Markdown Cells.
[Link]
[Link]/en/stable/examples/Notebook/Working%20With%20Markdo
wn%[Link]
• Gruber, J.. Markdown. [Link]

MSBD5001 Fall 2024 141

You might also like