0% found this document useful (0 votes)
3 views46 pages

Python & Jupyter Notebook Setup Guide

Uploaded by

baghdadi.absari
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)
3 views46 pages

Python & Jupyter Notebook Setup Guide

Uploaded by

baghdadi.absari
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

Software Engineering For

Data Science (SEDS)


Class: 2 Year 2nd Cycle
Branch: AIDS
Dr. Belkacem KHALDI| ESI-SBA
Lecture 02:

Getting Started with Python &


Jupyter Notebook
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 1
Getting Started with Python & Jupyter
Notebook
1. Introduction to Python
2. Introduction to Jupyter Notebooks
3. Python Basics

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 2
Introduction to Python
What is Python? Why Python?
● Python is a programming language ● Widely used programming language by Data
Scientists.
● Python is an interpreted language: lines of
● Multi-purpose language
code are executed one at a time.
● Great data science libraries (Extensible
● Python has two active versions: ecosystem)
■ Python 2.x ● Easy to learn / use

■ Python 3.x.
○ (caution: slight differences between
versions!)

[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 3
Introduction to Python
Installation and Setup:

• Use Anaconda distribution provided by


Continuum Analytics.
○ The easiest way to perform Python/R data
science and machine learning on a single
machine.
○ Comes with conda, Python, and over 150
scientific packages and their dependencies.
○ Offered in both Python 2.7 and 3.x.

Note: Your system may come shipped with a default Python interpreter. Even so, we strongly encourage to follow the steps
upcoming next in order to:
1. replicate the exact environment used in this class and
2. practice with possible installation/configuration issues. [Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 4
Introduction to Python
Installation and Setup:

Apple (OS X, macOS) Additional note for OS X and macOS


• Download the OS X Anaconda installer called • Alternative (not recommended!)
something like: - Install Python alone (via Homebrew)
•Anaconda3-2022.05-MacOSX-x86_64.pkg - Install each package you need via pip
• Double-click the .pkg file to run the installer.
• For those who are curious, please refer to this
tutorial:
• To verify everything is working, try launching [Link]
python from the Terminal application. nstall3/osx/

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 5
Introduction to Python
Installation and Setup:

GNU/Linux
• Depends on the Linux distributions: Debian, • Setup⇒ execute this script with bash:
Ubuntu, CentOS, and Fedora. bash Anaconda3-2022.05-Linux-x86_64.sh
• Depends on whether you have a 32-bit or 64-bit - The default directory installation:
system.
/home/$USER/anaconda.
- Install the x86 (32-bit) or x86_64 (64-bit)
installer.
- A file named something similar to:
Anaconda3-2022.05-Linux-x86_64.sh

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 6
Introduction to Python
Installation and Setup:

Windows
• Download the Anaconda installer for Windows • Make the Anaconda distribution the default Python
from on your system ⇒ add it to your PATH
[Link] environment variable (recommended).
an executable named like: • Verification:
Anaconda3-2022.05-Windows-x86_64.exe
- Open a command prompt (Start Menu -->
• Run the installer and accept the default installation Command Prompt application);
location. - Launch the Python interpreter
• In case you had previously installed Python in this
python
location, you may want to remove it first.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 7
Introduction to Python
Running a Python Code: The Python shell

• Using the REPL (Read-Eval-Print-Loop) (results


in real time, type code line-by-line) with:
○ Python Shell or,
○ IPython Shell.

○ Put your code in a file (e.g. [Link]), then


execute python [Link] in a terminal to run the
file line-by-line. The IPython shell

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 8
Introduction to Python
Installing Python Packages and Managing virtual
environments
● Packages extend python functionalities and make certain tasks easier,
such as building and running machine learning models.

○ Numpy
■ For Matrices, and N-Dim Arrays, and more
○ Scipy
■ For algorithms optimization, integration, interpolation,
eigenvalue problems, algebraic equations, differential equations,
statistics and many
○ Pandas
■ For Data analysis and manipulation
○ Scikit-learn
■ For Machine learning and predictive data analysis
○ TensorFlow and PyTorch
■ End-to-end advanced deep learning platform ecosystems

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 9
Introduction to Python
Installing Python Packages and Managing virtual
environments

Two primary ways to install and manage packages – conda and pip.
Pip: Conda:
○ The package installer for Python ○ The package manager that comes with the
○ The classic way to manage packages in Anaconda Python distribution
Python. ○ Conda has dependency resolution
■ Difficult when using pip
○ pip has no dependency resolution! ○ General Conda commands for packages:
○ General Pip commands:

pip install <PACKAGENAME> conda install <PACKAGENAME>


pip install --upgrade <PACKAGENAME> conda update <PACKAGENAME>
pip uninstall <PACKAGENAME> conda remove <PACKAGENAME>
pip freeze # Prints all versions conda list # list all packaged

● Upgrading a conda package with pip (or vice versa) will break stuff!

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 10
Introduction to Python
Installing Python Packages and Some useful Conda Environments Commands
Managing virtual environments #Creating env.
conda create --name <ENVNAME>
● Virtual environments ⇒ Separate Python conda create -n <ENVNAME>
installation to prevent overlap with the base conda create --clone <ENVNAME> --name <ENVNAME>
Python installation. conda env create --file <[Link]>
● Useful while conda create -n <ENVNAME> <PACKAGENAME>=<VERS>
○ Using different versions of Python (for #Activating or Deactivating an env.
example, 3.9 and 3.8) #Windows:
○ Having different virtual environments with activate
certain packages for different projects. deactivate
● Gain more reproducibility ⇒ so that the work #Linux and macOS:
runs in the same way no matter who runs it on conda activate
which computer. conda deactivate
● Many ways in which to run virtual #export environments for sharing or moving it
environments with Python: virtualenv,
conda env export --from-history > <[Link]>
venv, pipenv, conda, and more.
[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 11
Introduction to Python
VS Code Jupyter Notebook
Integrated Development
Environments (IDEs):

● IDEs provide productivity tools


such as syntax highlighting,
auto-completion, debugging, and
more rich features
○ Jupyter Notebook from Jupyter.
○ VS Code from Windows PyCharm Spyder
○ PyCharm from JetBrains
○ Spyder, an IDE currently shipped
with Anaconda.

Note: In this class, we will use Jupyter


Notebook. Let's see how to properly set
up Jupyter Notebook environment.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 12
Introduction to Jupyter Notebooks
Jupyter Notebooks: What?
• A Jupyter notebook (formerly IPython
Notebook) is a web-based interactive
computational environment for creating
notebook documents.

• It makes scientific programming interactive!

• It is among the top data scientists’


computational notebook of choice.
• Source:
• We will use Jupyter Notebooks with Python. - Perkel, J. M. (2018). Why Jupyter is data
scientists' computational notebook of
choice. Nature, 563(7732), 145-147.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 13
Introduction to Jupyter Notebooks
Jupyter Notebooks: Why?
• Jupyter Notebooks are documents that allow you to bring together
data, code, and prose, to tell an interactive, computational
story (.. All in one place).

• More engaging with practitioners.

• Adoption of literate programming by embracing standard web


technologies (i.e., mostly HTML5, JavaScript, and CSS)

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 14
Introduction to Jupyter Notebooks
Jupyter Notebook vs Jupyter Lab
• Both equally functional and compatible (but Lab is the Next-Generation Notebook Interface)

More Suitable for beginners

More Suitable for Advanced


users
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 15
Introduction to Jupyter Notebooks
Jupyter Notebook's Overall
Architecture
• Jupyter Notebook ⇒ IPython kernel (backend) +
the web-based interface provided with Notebook
(frontend).
- ⇒ Stores code and output in an editable document
called a notebook.
- ⇒ Saved on disk as a JSON file with a .ipynb
extension.
• Jupyter Notebook on a local machine without
Internet access: Fig. High-level architecture of Jupyter Notebook
- Via a web browser running on the same machine
where the Notebook server is running,
- Via on a remote server and accessed through the
Internet.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 16
Introduction to Jupyter Notebooks
Installation and Setup: Using Anaconda

Prerequisite: Python Interpreter • Open a shell and type:


- jupyter notebook
• Python is a requirement for installing Jupyter
Notebook.
• Python and Jupyter Notebook can be installed - Or launch it using the Anaconda Navigator
separately.

Installation
• Using Anaconda Python Distribution (highly
recommended)
• Using pip (only for skilled users).

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 17
Introduction to Jupyter Notebooks
Installation and Setup: Using Pip
• Better for experienced and skilled Python users.

Prerequisite: Python Interpreter


• Make sure you have the latest pip:
• Python is a requirement for installing Jupyter - # Python 3.3 or above:
Notebook. - pip3 install upgrade pip
- # Python 2.7.x:
• Python and Jupyter Notebook can be installed - pip install upgrade pip
separately.

• Install Jupyter Notebook as follows:


Installation - # Python 3.3 or above
- pip3 install jupyter
• Using Anaconda Python Distribution (highly - # Python 2.7.x
recommended) - pip install jupyter
• Using pip (only for skilled users).
• Run the Jupyter Notebook application in a shell
command:
- jupyter notebook

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 18
Introduction to Jupyter Notebooks
Jupyter Notebook UI Components:
• Notebook Dashboard
- When you launch jupyter notebook the first page that you encounter is the Notebook Dashboard.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 19
Introduction to Jupyter Notebooks
Jupyter Notebook UI Components:
• Notebook Editor
- Once you’ve selected a Notebook to edit, the Notebook will open in the Notebook Editor.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 20
Introduction to Jupyter Notebooks
Jupyter Notebook UI Components:
• Edit Mode and Notebook Editor
- A Cell’s state can be changed to edit mode.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 21
Introduction to Jupyter Notebooks
Jupyter Notebook UI
Components:

• Two main types of cells:


Markdown cells and Code cells.
- A Markdown cell: Rich text with
classic formatting options: (e.g.:
bold or italics), + advanced features
(e,g.: links, images, HTML
elements, LaTeX mathematical
equations, and much more.

- A Code cell: Code to be executed


by the kernel.

Fig. An Example of a Jupyter Notebook Document


Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 22
Introduction to Jupyter Notebooks
Markdown Cells
• Jupyter Notebook uses
Markdown for the text
formatting.

• Markdown is a minimal
language for formatting text.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 23
Introduction to Jupyter Notebooks
Markdown Cells: Basic Syntax
Element Markdown Syntax Element Markdown Syntax
Heading # H1 Code `code`
## H2
### H3
Horizontal Rule ---
Bold **bold text**
Link [title]([Link]
Italic *italicized text* [Link])

Image ![alt text]([Link])


Blockquote > blockquote

Ordered List 1. First item


2. Second item
3. Third item

Unordered List - First item


- Second item For more advanced Markdown Syntax:
- Third item [Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 24
Introduction to Jupyter Notebooks
Code Cells

• Cells are numbered by execution sequence [1],


[2], …

• Busy cells show an asterisk sign [*] to signify


that the code is still being evaluated.

• The blue bar signifies which cell is selected.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 25
Introduction to Jupyter Notebooks
Getting help in Jupyter
• ? gives a bit more information than help
• We can also use the Help dropdown from the menu bar

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 26
Introduction to Jupyter Notebooks
Keyboard shortcuts Keyboard Shortcuts (Available in Both Modes)

• All operations can be done Shortcut Usage


using keyboard shortcuts.
Ctrl + Enter Run the cell
- They are listed besides every Alt + Enter Run the cell and insert a new cell below
operation in the Jupyter
toolbar.
Shift + Enter Run the cell and select the cell below

Ctrl + S Save the notebook

Keyboard Shortcuts (Available in the Edit Mode)

Shortcut Usage
Esc Switch to command mode
Note: Some keyboard shortcuts may be
different on different platforms
Ctrl + Shift + - Split the cell
(Windows/Linux and Mac)
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 27
Introduction to Jupyter Notebooks
Keyboard shortcuts Keyboard Shortcuts (Available in the Command Mode)

• All operations can be done Shortcut Usage


using keyboard shortcuts.
Enter Switch to edit mode
- They are listed besides every Up or K Select the previous cell
operation in the Jupyter
toolbar. Down or J Select the next cell

Y/M Change the cell type to Code cell/Markdown cell

A/B Insert a new cell above/below the current cell

X/C/V Cut/Copy/Paste the current cell

DD Delete the current cell

Shift + M Merge multiple cells into a single one


Note: Please, have a look at 28 Jupyter
Notebook tips, tricks and shortcuts and H Display the help menu with the list of keyboard shortcuts
Jupyter (IPython) notebooks features
for any further details.
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 28
Introduction to Jupyter Notebooks
Advanced Features
Share Jupyter Notebooks
• Notebooks: documents saved as JSON files.
• We don't want to share our notebooks with others
as JSON files.

• Jupyter allows to download your notebook as:


- Notebook (.ipynb),
- Python script (.py),
- HTML (.html),
- Markdown (.md),
- reStructuredText (.rst),
- LaTeX (.tex)
- PDF (.pdf) file, ….

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 29
Introduction to Jupyter Notebooks
Advanced Features
Converting Jupyter Notebook to Slides
• Jupyter can convert a notebook into an online slide deck
for talks and tutorials.
• To convert a notebook into a [Link] presentation, go to
the View menu and set Cell Toolbar to Slideshow.
• Organize the cells of your notebook into slides and
sub-slides.

• Convert it to the slide format using nbconvert as follows:


jupyter nbconvert {NOTEBOOK_NAME}.ipynb to slide --post serve
• This will generate a {NOTEBOOK_NAME}.[Link] file in the same directory of your notebook file
• You can open it on a new tab of your system default browser at
[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 30
Introduction to Jupyter Notebooks
Advanced Features
Converting Jupyter Notebook
to Slides

• Output Result Example

• You may apply templates


from github projects to
customize and build attractive
slides.

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 31
Introduction to Jupyter Notebooks
Advanced Features
Converting Jupyter Notebook to Slides

• An alternative way with RISE Plugin:


• Install RISE plugin as a Jupyter Notebook
extension as follows:
- conda install -c conda-forge rise
- pip install rise

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 32
Python Basics
Identifiers Keywords
• Identifiers are the names we give to variables, • Keywords are special words are reserved by
functions,... Python and cannot be used as identifiers
• Can only contain alphanumeric and •
underscore (A-z,0-9,_)
- nbr_students, seds_marks, #students
• Cannot start with a number
- student_01_mark, 01_students_mark
• Names are case-sensitive
- age, Age, AGE are all different! • They are typically highlighted in a special way in
the IDE)

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 33
Python Basics
Comments Basic Data Types
• Comments are annotations used to make code • Different Data Types:
more readable by others (and yourself, later!). Use - Basic Built-In: integer, float, boolean, str,...
them!
- Compound data types: list, tuple, dict, and set
• Single line comments are put after a hashtag
• Data Types also determine whether a certain
# This is a single Line comment operation makes sense for an object.
# Addition, returns 12
• Multiline comments are put between three quotes 5 + 7
""" # Concatenation, returns 'DataScience'
multi-line 'Data' + 'Science'
comments # Error! Makes no sense!
can be done like this 5 + 'Science'
""" # Concatenation, returns '5Data'
'5' + 'Data'

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 34
Python Basics
Basic Data Types
• Basic Built-in Data Types

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 35
Python Basics
● Common built-in functions for Lists
Basic Data Types L2+L3 Returns a concatenated list with (['a', 'b', 'c', 2, 0, 4])
• Compound Data Types: (list)
[Link]('d') Appends 'd' to the end of the list (L2 == ['a', 'b', 'c', 'd'])
Combine basic data types together
[Link](['d', 'e']) Appends every element of the iterable to the end of the list (L2 ==
- List: Used to store multiple ['a', 'b', 'c', 'd', 'e'])
items in a single variable.
[Link](1, 'd') Inserts 'd' to index 1 of L2 (L2 == ['a', 'd', 'b', 'c'])
- lists are created using []:
[Link]() Returns the last element of the list and deletes it from the list. ('c')
- Lists have mutable nature
(can be changed or modified [Link]('b') Removes first occurrence of 'b' in L2 (L2 == ['a', 'c'])
after creation) [Link]() Clears the list entirely (L2 == [])
L1 = [100,"hundred","100",2.14e3]
[Link]() Returns a sorted version of L3 ([0, 2, 4])
L2 = ['a','b','c']
L3 = [2, 0, 4] [Link]() Returns a copy of L3
- Iterating over a list: [Link]() Reverses the list L3 ([4, 0, 2])

for ele in L2 len(L1) Returns the number of elements in L1 (4)


print(ele)
[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 36
Python Basics
Basic Data Types ● Common built-in functions for Tuples
• Compound Data Types: (tuple)
T2+T3 Returns a concatenated version of T1 and T2
Combine basic data types together
- Tuples: Similar to a list, used len(T1) Returns the number of elements in T1 (4)
to store multiple items in a [Link](2) Returns the number of occurrences of 2 in t3 (1)
single variable.
- Tuples are created using (): [Link](1) Returns the index of the 1st occurrence of 1 (-1)

- Tuples have immutable Note: count() and index() methods work with Lists as well.
nature (can’t be changed or
modified after creation)
T1 = (100,"hundred","100",2.14e3)
T2 = ('a','b','c')
T3 = (2, 0, 4)
- Iterating over a tuple:

for ele in T2
print(ele)
[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 37
Python Basics
Basic Data Types - Slicing: Can specify start, end, and step
length to access a range of elements.
• Compound Data Types: (list, tuple)
Combine basic data types together
- Indexing: Each item can be referenced from
start or end

print(X[1:4]) #['b','c','d']
print(X[3:]) #['d','e','f','g']
print(X[5] + X[-7] + X[-5] + X[4]) print(X[-5:5]) #['c','d','e']
print(X[0:4:2]) #['a','c']
'face'
print(X[:3]) #['a','b','c']
print(X[3::-1]) #['d','c','b','a']

More Information: Python Tuples vs Lists ([Link]


Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 38
Python Basics db={'Ali': {'high_school': 'Ali Mellah',
'college': 'ESI-SBA',
'age': 19,
Basic Data Types 'scores': [75,86,92]
},
• Compound Data Types: (dict) 'Ahmed':{'high_school': 'El Idrissi',
Combine basic data types together 'college': 'ESI-ALG',
'age': 22,
- Dictionaries (dict) are similar to lists, except
'scores': [71,95,84]
they are indexed using strings (keys) rather }
than integers. }
- dict can be seen as a set of key:value pairs, db['Ali']['college']
with the requirement that the keys are unique. ESI-SBA

- Iterating over a dict:


Ages={Ali:19, 'Ahmed':22}
ages['Ahmed'] for key, value in [Link]():
print(f'{key}:{value}')
22
Ali:{'high_school': 'Ali Mellah', 'college': 'ESI-SBA', 'age': 19, 'scores': [75, 86, 92]}
scores={'Ali':[75,86,92],'Ahmed':[71,95,84]} Ahmed:{'high_school': 'El Idrissi', 'college': 'ESI-ALG', 'age': 22, 'scores': [71, 95, 84]}
scores['Ahmed']
[71,95,84]
[Link]
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 39
Python Basics - Many Possible Representations
Row-first:
data = {'London':{'Area':1572,
Basic Data Types 'Population':8.61
• Compound Data Types: (dict) },
'Berlin': {'Area':891.70,
- Tabular Data Example: 'Population':3.56
Each row: one observation },
Each column: features of each observation …
}
City Area Population
in (Km2) in (Millions) Column-first:

London 1,572.00 8.61 data = { 'Area': { 'London':1572,


'Berlin':891.70,
Berlin 891.70 3.56 …
Madrid 604.31 3.16 }
'Population': { 'London':8.61,
Rome 1,285.00 2.87 'Berlin':3.56,

Paris 105.40 2.27
}
… … … }

What is the standard and better way to handle and represent tabular data?
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 40
Python Basics
Basic Data Types
• Compound Data Types:
(dict)
- Tabular Data Example:
- Using Pandas
DataFrame:
Pandas ⇒ a Python
package providing fast,
flexible, and expressive data
structures designed to make
working with “relational”
or “labeled” data both easy
and intuitive.
Pandas ⇒ the fundamental
high-level building block for
doing practical, real world
data analysis in Python.
Note: More Details will be available in the
upcoming Chapters
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 41
Python Basics
Functions
• Built-In • Positional vs Named arguments
- Part of Python packages/libraries. - Specify a default value to make an argument optional.
Examples:
from math import sqrt def weather( day = 'Monday', forecast = 'cloudy' ):
print("Hello World!") print('It will be', forecast, 'on', day)
sqrt(91)

• User-Defined - Arguments can be specified positionally or by name.

- Written by the user to achieve a


specific purpose. #It will be cloudy on Monday
weather()
- Can be created/modified as required, #It will be sunny on Tuesday
def density(area,population):
unlike built-in functions. Example
dens = population/area weather('Tuesday','sunny')
return dens #It will be rainy on Monday
weather(forecast='rainy')
#It will be dry on Friday
weather(forecast='dry', day='Friday')
Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 42
Python Basics
Packages • Import all functionalities from Packages
• Packages( Libraries) ⇒ makes Python
import numpy as np
so powerful for data science.
a=[Link]([1,2,3])
• Each package adds new functionality
that wasn't there before. • Import a specific function from a package
• Python has a host of built-in packages
from math import sqrt, sin
providing basic functionality, but the
real power comes from community b=sin(45)*sqrt(30)
packages on GitHub and PyPI. • Import a Sub-Package
• A package can be:
- A collections of Python files: numpy, import [Link]
pandas, …. [Link]('[Link]
- Individual Python files: time, math,….
- Sometimes, packages have
• Best way to shorten the long call
sub-packages.
from [Link] import urlopen
urlopen('[Link]

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 43
Python Basics
Diagnosing Errors & Debugging
• Diagnosing errors:
- Python comes with a traceback module for Fig.: An example of an error in Jupyter Notebook (ipython)
reporting errors in coding.
- traceback contains all of the information you’ll
need to diagnose the issue .
- Always look to the final line of the traceback
output ⇒ The type of exception raised + some
relevant information about that exception.
- Previous lines of the traceback ⇒ point out the
code that resulted in the exception being raised.

Fig.: An example of an error in python shell


Dr. Belkacem KHALDI
e-mail: [Link]@[Link] 44
Python Basics
Useful pdb commandes
Diagnosing Errors & Debugging n(ext) Step over
● Debugging errors:
s(tep) Step into
○ Python Debugging Module: pdb.
○ How to Use It? r(eturn) Continue until the current function returns

■ Start pdb inside a python script: c(ontinue) Continue until the next breakpoint is
encountered
■import pdb; pdb.set_trace()
h(elp) Show help
■ Start pdb from the command line b(reak) [#] Show all breakpoints or Set a breakpoint
at a line #.
python -m pdb <[Link]>
clear number Remove breakpoint number
○ Running the code ⇒ the execution stops on the line p(rint) variable Print the value of a variable
and allows to type in pdb commandes to start
debugging. a(rgs) Print the arguments of the current function

q(uit) Quit debugger

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 45
Thanks for your Listening

Dr. Belkacem KHALDI


e-mail: [Link]@[Link] 46

You might also like