PYTHON: A brief introduction for beginners

sushanbairy 8 views 251 slides Feb 27, 2025
Slide 1
Slide 1 of 251
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251

About This Presentation

A brief introduction to Python is given in the slides


Slide Content

PYTHON - An Introduction
K SUSHAN BAIRY
Department of Mathematics, School of Applied Sciences,
Reva University, Kattigenahalli,
Bengaluru-560 064, INDIA.
Mobile:+91 9480330198
email:[email protected]
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 1 / 118

Introduction to PYTHON What is PYTHON?
WHAT ISPYTHON?
Python is a computer programming language.
Guido van Rossum (1987) named it after the BBC television show ‘Monty Python’s
Flying Circus.’
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 2 / 118

Introduction to PYTHON What is PYTHON?
WHAT ISPYTHON?
Python is a computer programming language.
Guido van Rossum (1987) named it after the BBC television show ‘Monty Python’s
Flying Circus.’
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 2 / 118

Introduction to PYTHON History
HISTORY
Created in early 1990’s – Guido van Rossum at Stichting Mathematisch Centrum
(CWI, see https://www.cwi.nl/), Netherlands as a successor of a language called ABC.
1995 – Guido continued work on Python at Corporation for National Research Initia-
tives (CNRI, see https://www.cnri.reston.va.us/) in Reston, Virginia.
May 2000 – Guido and the Python core development team move to BeOpen.com to
form the BeOpen PythonLabs team.
October 2000 – PythonLabs team moved to Digital Creations (now Zope Corporation). 2001 – Python Software Foundation (PSF) was formed. (Zope corporation is a spon-
soring member.)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 3 / 118

Introduction to PYTHON History
HISTORY
Created in early 1990’s – Guido van Rossum at Stichting Mathematisch Centrum
(CWI, see https://www.cwi.nl/), Netherlands as a successor of a language called ABC.
1995 – Guido continued work on Python at Corporation for National Research Initia-
tives (CNRI, see https://www.cnri.reston.va.us/) in Reston, Virginia.
May 2000 – Guido and the Python core development team move to BeOpen.com to
form the BeOpen PythonLabs team.
October 2000 – PythonLabs team moved to Digital Creations (now Zope Corporation). 2001 – Python Software Foundation (PSF) was formed. (Zope corporation is a spon-
soring member.)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 3 / 118

Introduction to PYTHON History
HISTORY
Created in early 1990’s – Guido van Rossum at Stichting Mathematisch Centrum
(CWI, see https://www.cwi.nl/), Netherlands as a successor of a language called ABC.
1995 – Guido continued work on Python at Corporation for National Research Initia-
tives (CNRI, see https://www.cnri.reston.va.us/) in Reston, Virginia.
May 2000 – Guido and the Python core development team move to BeOpen.com to
form the BeOpen PythonLabs team.
October 2000 – PythonLabs team moved to Digital Creations (now Zope Corporation). 2001 – Python Software Foundation (PSF) was formed. (Zope corporation is a spon-
soring member.)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 3 / 118

Introduction to PYTHON History
HISTORY
Created in early 1990’s – Guido van Rossum at Stichting Mathematisch Centrum
(CWI, see https://www.cwi.nl/), Netherlands as a successor of a language called ABC.
1995 – Guido continued work on Python at Corporation for National Research Initia-
tives (CNRI, see https://www.cnri.reston.va.us/) in Reston, Virginia.
May 2000 – Guido and the Python core development team move to BeOpen.com to
form the BeOpen PythonLabs team.
October 2000 – PythonLabs team moved to Digital Creations (now Zope Corporation). 2001 – Python Software Foundation (PSF) was formed. (Zope corporation is a spon-
soring member.)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 3 / 118

Introduction to PYTHON History
HISTORY
Created in early 1990’s – Guido van Rossum at Stichting Mathematisch Centrum
(CWI, see https://www.cwi.nl/), Netherlands as a successor of a language called ABC.
1995 – Guido continued work on Python at Corporation for National Research Initia-
tives (CNRI, see https://www.cnri.reston.va.us/) in Reston, Virginia.
May 2000 – Guido and the Python core development team move to BeOpen.com to
form the BeOpen PythonLabs team.
October 2000 – PythonLabs team moved to Digital Creations (now Zope Corporation). 2001 – Python Software Foundation (PSF) was formed. (Zope corporation is a spon-
soring member.)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 3 / 118

Introduction to PYTHON History
PYTHON USED FOR...
Python is used in many places.
One can use Python to automate tasks, perform calculations, create user interfaces,
create website backends, access databases, download information from the Internet,
etc.
One of the recent growing field of expertise is ‘data science’. Many data scientists use
Python for their day-to-day work.
Python includes a comprehensive base library.
Addition to this, One can find hundreds of thousands of external packages contributed
by the enormous community. You’ll find supporting base libraries and packages for
pretty much anything you want to accomplish.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 4 / 118

Introduction to PYTHON History
PYTHON USED FOR...
Python is used in many places.
One can use Python to automate tasks, perform calculations, create user interfaces,
create website backends, access databases, download information from the Internet,
etc.
One of the recent growing field of expertise is ‘data science’. Many data scientists use
Python for their day-to-day work.
Python includes a comprehensive base library.
Addition to this, One can find hundreds of thousands of external packages contributed
by the enormous community. You’ll find supporting base libraries and packages for
pretty much anything you want to accomplish.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 4 / 118

Introduction to PYTHON History
PYTHON USED FOR...
Python is used in many places.
One can use Python to automate tasks, perform calculations, create user interfaces,
create website backends, access databases, download information from the Internet,
etc.
One of the recent growing field of expertise is ‘data science’. Many data scientists use
Python for their day-to-day work.
Python includes a comprehensive base library.
Addition to this, One can find hundreds of thousands of external packages contributed
by the enormous community. You’ll find supporting base libraries and packages for
pretty much anything you want to accomplish.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 4 / 118

Introduction to PYTHON History
PYTHON USED FOR...
Python is used in many places.
One can use Python to automate tasks, perform calculations, create user interfaces,
create website backends, access databases, download information from the Internet,
etc.
One of the recent growing field of expertise is ‘data science’. Many data scientists use
Python for their day-to-day work.
Python includes a comprehensive base library.
Addition to this, One can find hundreds of thousands of external packages contributed
by the enormous community. You’ll find supporting base libraries and packages for
pretty much anything you want to accomplish.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 4 / 118

Introduction to PYTHON History
PYTHON USED FOR...
Python is used in many places.
One can use Python to automate tasks, perform calculations, create user interfaces,
create website backends, access databases, download information from the Internet,
etc.
One of the recent growing field of expertise is ‘data science’. Many data scientists use
Python for their day-to-day work.
Python includes a comprehensive base library.
Addition to this, One can find hundreds of thousands of external packages contributed
by the enormous community. You’ll find supporting base libraries and packages for
pretty much anything you want to accomplish.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 4 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON History
PYTHON’S MAJOR FEATURES
It is easy to read and write.
Python is an interpreted, interactive, object-oriented programming language It incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.
It has interfaces to many system calls and libraries, as well as to various window
systems.
It is used as an extension language for applications that need a programming
interface.
Python is portable: it runs on many Unix variants including Linux and macOS, and on
Windows.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 5 / 118

Introduction to PYTHON Anaconda
INTRODUCTION TO ANACONDA
Anaconda is a package manager, environment manager, and Python distribution with
a collection of 1,500+ open source packages with free community support. Anaconda
is free and easy to install and can be used on Windows, macOS, or Linux.
Anaconda can be downloaded from
https://www.anaconda.com/products/individual
After installing Anaconda, we use Anaconda Navigator to launch applications and
easily manage packages, environments and channels without using command-line
commands.
Navigator is an easy, point-and-click way to work with packages and environments
without needing to type conda commands in the terminal window.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 6 / 118

Introduction to PYTHON Anaconda
INTRODUCTION TO ANACONDA
Anaconda is a package manager, environment manager, and Python distribution with
a collection of 1,500+ open source packages with free community support. Anaconda
is free and easy to install and can be used on Windows, macOS, or Linux.
Anaconda can be downloaded from
https://www.anaconda.com/products/individual
After installing Anaconda, we use Anaconda Navigator to launch applications and
easily manage packages, environments and channels without using command-line
commands.
Navigator is an easy, point-and-click way to work with packages and environments
without needing to type conda commands in the terminal window.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 6 / 118

Introduction to PYTHON Anaconda
INTRODUCTION TO ANACONDA
Anaconda is a package manager, environment manager, and Python distribution with
a collection of 1,500+ open source packages with free community support. Anaconda
is free and easy to install and can be used on Windows, macOS, or Linux.
Anaconda can be downloaded from
https://www.anaconda.com/products/individual
After installing Anaconda, we use Anaconda Navigator to launch applications and
easily manage packages, environments and channels without using command-line
commands.
Navigator is an easy, point-and-click way to work with packages and environments
without needing to type conda commands in the terminal window.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 6 / 118

Introduction to PYTHON Anaconda
INTRODUCTION TO ANACONDA
Anaconda is a package manager, environment manager, and Python distribution with
a collection of 1,500+ open source packages with free community support. Anaconda
is free and easy to install and can be used on Windows, macOS, or Linux.
Anaconda can be downloaded from
https://www.anaconda.com/products/individual
After installing Anaconda, we use Anaconda Navigator to launch applications and
easily manage packages, environments and channels without using command-line
commands.
Navigator is an easy, point-and-click way to work with packages and environments
without needing to type conda commands in the terminal window.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 6 / 118

Introduction to PYTHON Anaconda
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 7 / 118

Introduction to PYTHON Anaconda
APPLICATIONS INNAVIGATOR
The following applications are available by default in Navigator:
JupyterLab
Jupyter Notebook
Spyder
PyCharm
VSCode
Glueviz
Orange 3 App
RStudio
Anaconda Prompt (Windows only)
Anaconda PowerShell (Windows only)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 8 / 118

Introduction to PYTHON Anaconda
JUPYTERNOTEBOOK
The notebook extends the console-based approach to interactive computing in a quali-
tatively new direction, providing a web-based application suitable for capturing the whole
computation process: developing, documenting, and executing code, as well as communi-
cating the results.
The Jupyter notebook combines two components:A web application:a browser-based tool for interactive authoring of documents which
combine explanatory text, mathematics, computations and their rich media output.
Notebook documents:a representation of all content visible in the web application, in-
cluding inputs and outputs of the computations, explanatory text, mathematics, images,
and rich media representations of objects.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 9 / 118

Introduction to PYTHON Anaconda
JUPYTERNOTEBOOK
The notebook extends the console-based approach to interactive computing in a quali-
tatively new direction, providing a web-based application suitable for capturing the whole
computation process: developing, documenting, and executing code, as well as communi-
cating the results.
The Jupyter notebook combines two components:A web application:a browser-based tool for interactive authoring of documents which
combine explanatory text, mathematics, computations and their rich media output.
Notebook documents:a representation of all content visible in the web application, in-
cluding inputs and outputs of the computations, explanatory text, mathematics, images,
and rich media representations of objects.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 9 / 118

Introduction to PYTHON Anaconda
JUPYTERNOTEBOOK
The notebook extends the console-based approach to interactive computing in a quali-
tatively new direction, providing a web-based application suitable for capturing the whole
computation process: developing, documenting, and executing code, as well as communi-
cating the results.
The Jupyter notebook combines two components:A web application:a browser-based tool for interactive authoring of documents which
combine explanatory text, mathematics, computations and their rich media output.
Notebook documents:a representation of all content visible in the web application, in-
cluding inputs and outputs of the computations, explanatory text, mathematics, images,
and rich media representations of objects.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 9 / 118

Introduction to PYTHON Anaconda
JUPYTERNOTEBOOK
The notebook extends the console-based approach to interactive computing in a quali-
tatively new direction, providing a web-based application suitable for capturing the whole
computation process: developing, documenting, and executing code, as well as communi-
cating the results.
The Jupyter notebook combines two components:A web application:a browser-based tool for interactive authoring of documents which
combine explanatory text, mathematics, computations and their rich media output.
Notebook documents:a representation of all content visible in the web application, in-
cluding inputs and outputs of the computations, explanatory text, mathematics, images,
and rich media representations of objects.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 9 / 118

Introduction to PYTHON Anaconda
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 10 / 118

Introduction to PYTHON Anaconda
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 11 / 118

Introduction to PYTHON Installing Python
DOWNLOAD AND DOCUMENTATION
Python home -https://www.python.org/
Download area -https://www.python.org/downloads/
Documentation and Help -https://www.python.org/doc/
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 12 / 118

Introduction to PYTHON Installing Python
INSTALLINGPYTHON
NOTE:
Python 3.10 supports Windows 8.1 and newer. If you require Windows 7 support, please
install Python 3.8.
For full installation: download “Python 3.10” installer available for download.
The following dialogue box appears.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 13 / 118

Introduction to PYTHON Installing Python
INSTALLINGPYTHON
NOTE:
Python 3.10 supports Windows 8.1 and newer. If you require Windows 7 support, please
install Python 3.8.
For full installation: download “Python 3.10” installer available for download.
The following dialogue box appears.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 13 / 118

Introduction to PYTHON Installing Python
Select any one of the option and continue.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 14 / 118

Introduction to PYTHON Installing Python
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 15 / 118

Introduction to PYTHON Installing Python
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 16 / 118

Introduction to PYTHON Installing Python
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 17 / 118

Introduction to PYTHON Installing Python
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 18 / 118

Introduction to PYTHON Installing Python
This completes the successful installation of “Python 3.10.0”.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 19 / 118

Introduction to PYTHON INSTALLING PACKAGES FOR PYTHON
INSTALLING PACKAGES FOR PYTHON
Open command prompt by searchingcmd
pip (package installer for Python) is used to install packages from Python Package
Index and other indexes. First we update the ‘pip’ to latest version and then use pip to
install the packages.
Type: python -m pip install - -upgrade pip
pip install numpy
pip install sympy
pip install matplotlib
pip install statistics
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 20 / 118

Introduction to PYTHON INSTALLING PACKAGES FOR PYTHON
INSTALLING PACKAGES FOR PYTHON
Open command prompt by searchingcmd
pip (package installer for Python) is used to install packages from Python Package
Index and other indexes. First we update the ‘pip’ to latest version and then use pip to
install the packages.
Type: python -m pip install - -upgrade pip
pip install numpy
pip install sympy
pip install matplotlib
pip install statistics
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 20 / 118

Introduction to PYTHON Shell/Editor
SHELL/EDITOR
SHELL/EDITOR
Open IDLE (Integrated Development and Learning Environment). IDLE shell opens
and one can start working
Select “New File” from “File” menu.
The Editor will open. We type Python program here and then use the interpreter to
execute the content from the file.
Files to be saved with extension .py
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 21 / 118

Introduction to PYTHON Shell/Editor
SHELL/EDITOR
SHELL/EDITOR
Open IDLE (Integrated Development and Learning Environment). IDLE shell opens
and one can start working
Select “New File” from “File” menu.
The Editor will open. We type Python program here and then use the interpreter to
execute the content from the file.
Files to be saved with extension .py
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 21 / 118

Introduction to PYTHON Shell/Editor
SHELL/EDITOR
SHELL/EDITOR
Open IDLE (Integrated Development and Learning Environment). IDLE shell opens
and one can start working
Select “New File” from “File” menu.
The Editor will open. We type Python program here and then use the interpreter to
execute the content from the file.
Files to be saved with extension .py
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 21 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
KEYWORDS AND IDENTIFIERS
Keywordsare the reserved words in Python used by Python interpreter to recognize
the structure of the program.
Identifiersare the name given to entities like class, functions, variables etc. It helps
to differentiate one entity from another.
Identifiers can be a combination of letters from “a” to “z”, from “A” to “Z” and digits
from “0” to “9” or special character _,.
Keywords cannot be used as identifiers. Only special character used in identifiers is _. Identifier can be of any length.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 22 / 118

Keywords and Identifiers
VARIABLES
A variable is a named location used to store data in the memory.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variable names can be created using all ASCII letters from “a” to “z”, from “A” to “Z”
and digits from “0” to “9” are allowed, with the additional characters _.
Python is case sensitive, which means that upper and lower case letters are
considered to be different.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 23 / 118

Keywords and Identifiers
VARIABLES
A variable is a named location used to store data in the memory.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variable names can be created using all ASCII letters from “a” to “z”, from “A” to “Z”
and digits from “0” to “9” are allowed, with the additional characters _.
Python is case sensitive, which means that upper and lower case letters are
considered to be different.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 23 / 118

Keywords and Identifiers
VARIABLES
A variable is a named location used to store data in the memory.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variable names can be created using all ASCII letters from “a” to “z”, from “A” to “Z”
and digits from “0” to “9” are allowed, with the additional characters _.
Python is case sensitive, which means that upper and lower case letters are
considered to be different.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 23 / 118

Keywords and Identifiers
VARIABLES
A variable is a named location used to store data in the memory.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variable names can be created using all ASCII letters from “a” to “z”, from “A” to “Z”
and digits from “0” to “9” are allowed, with the additional characters _.
Python is case sensitive, which means that upper and lower case letters are
considered to be different.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 23 / 118

Keywords and Identifiers
VARIABLES
A variable is a named location used to store data in the memory.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variable names can be created using all ASCII letters from “a” to “z”, from “A” to “Z”
and digits from “0” to “9” are allowed, with the additional characters _.
Python is case sensitive, which means that upper and lower case letters are
considered to be different.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 23 / 118

Keywords and Identifiers
EXAMPLES:
a=2.4
x=3
y = ’a ’
z =" Hello "
p r i n t ( type ( a ) ) #type ( ) gives the data type of the v a r i a b l e .
p r i n t ( type ( x ) )
p r i n t ( type ( y ) )
p r i n t ( type ( z ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 24 / 118

Keywords and Identifiers
MOST IMPORTANTPYTHON KEYWORDS
def if elif else
for while in is
False True and or
not break continue class
None lambda return print
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 25 / 118

Keywords and Identifiers
DATA TYPES
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 26 / 118

Keywords and Identifiers
DATA TYPES
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 26 / 118

Keywords and Identifiers
DATA TYPES
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 26 / 118

Keywords and Identifiers
EXAMPLE FORNUMERIC TYPES:
x = 1 # i n t
y = 2.8 # f l o a t
z = 1 j # complex
X = 35e3 # e i n d i c a t e s the power of 10
Y = 12E4
Z = −87.7e100
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 27 / 118

Keywords and Identifiers
EXAMPLE FORTEXT TYPE:
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
a = " Hello "
p r i n t ( a )
b = " " " Lorem ipsum dolor s i t amet ,
consectetur a d i p i s c i n g e l i t ,
sed do eiusmod tempor i n c i d i d u n t
ut labore et dolore magna aliqua . " " "
p r i n t ( b )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 28 / 118

Keywords and Identifiers
EXAMPLE FORTEXT TYPE:
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
a = " Hello "
p r i n t ( a )
b = " " " Lorem ipsum dolor s i t amet ,
consectetur a d i p i s c i n g e l i t ,
sed do eiusmod tempor i n c i d i d u n t
ut labore et dolore magna aliqua . " " "
p r i n t ( b )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 28 / 118

Using Python as a Calculator
USINGPYTHON AS ACALCULATOR
Start the interpreter and wait for the primary prompt,>>>.
The interpreter acts as a scientific calculator: one can type an expression at it and it
will write the value. The syntax for expression is straightforward: the operators
+−,∗, /work just like in most other languages; parentheses (()) can be used for
grouping.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 29 / 118

Using Python as a Calculator
USINGPYTHON AS ACALCULATOR
Start the interpreter and wait for the primary prompt,>>>.
The interpreter acts as a scientific calculator: one can type an expression at it and it
will write the value. The syntax for expression is straightforward: the operators
+−,∗, /work just like in most other languages; parentheses (()) can be used for
grouping.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 29 / 118

Operators
OPERATORS
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 30 / 118

Operators
ARITHMETICOPERATORS
All the common algebraic operators presented in the following table are available in Python.
Addition +
Subtraction −
Multiplication∗
Division /
Integer Division//
Power **
Remainder %
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 31 / 118

Operators
COMPARISONOPERATORS
Comparison operators:
< less than
> greater than
<=less than or equal to
>=greater than or equal to
==equal to
! =not equal to
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 32 / 118

Operators
LOGICAL OPERATORS
Logical operators:
and logical and
or logical or
not logical not
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 33 / 118

Operators
ASSIGNMENTOPERATOR
=, is used as assignment operator. For examplex=5, means 5 is stored to variable
x.
+ =. The expressiona+ =3, give the result ofa=a+3.
−=. The expressionx−=3, give the result ofx=x−3.
∗=. The expressiona∗=3, give the result ofa=a∗3.
/=. The expressiona/=3, give the result ofa=a/3.
//=. The expressiona//=3, give the result ofa=a//3.
% =. The expressiona% =3, give the result ofa=a%3.
∗∗=. The expressiona∗=3, give the result ofa=a∗ ∗3.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 34 / 118

Operators
IDENTITYOPERATORS
Identity Operators
is Returns True if both variables are
the same object
is not Returns True if both variables are
not the same object
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 35 / 118

Operators
MEMBERSHIPOPERATORS
Membership Operators
in Returns True if a sequence with the
specified value is present in the ob-
ject
not in Returns True if a sequence with the
specified value is not present in the
object
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 36 / 118

Operators
EXERCISE:
Type the following statements and observe the output:
>>> 32+56−74
*
2+65/5−2
**
3
>>> 32+(56 −74)
*
2+65/5 −2
**
3
>>> 32+(56 −74)
*
2+(65/5 −2)
**
3
>>> 1254//9
>>> 487
**
2%3
>>> i n t ( 2 2 / 6 )
>>> round ( 2 2 / 6 )
>>> round (22/6 ,2)
>>> round (22/6 ,6)
>>> round ( 2 . 4 9 )
>>> round ( 2 . 5 )
>>> round ( 3 . 5 )
>>> round ( 3 . 5 1 )
>>> round ( 2 . 5 2 )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 37 / 118

Operators
EXERCISE:
Type the following statements and observe the output:
>>> x=23145621.456872194
>>> x
>>> round ( x )
>>> round ( x , 1 )
>>> round ( x , 2 )
>>> round ( x , 4 )
>>> round ( x , 6 )
>>> round ( x , −1)
>>> round ( x , −2)
>>> round ( x , −4)
>>> round ( x , −7)
>>> round ( x , −8)
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 38 / 118

Operators
EXERCISE:
Type the following statements and observe the output:
>>> x , y , z=23 ,45 ,67
>>> x+y , x+y+z , x
*
y
>>> p r i n t ( x+y , x+y+z , x
*
y )
>>> x
>>> x+=2
>>> x
>>> x−=4
>>> x
>>> x
*
=2
>>> x
>>> x%=2
>>> x
>>> x / / = 5
>>> x
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 39 / 118

Lists, Tuples, Sets, Dictionaries
Lists
Tuples
Sets
Dictionaries
These are used to store collections of data.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 40 / 118

Lists, Tuples, Sets, Dictionaries
LISTS, TUPLES
are used to store multiple items in a single variable.
Lists are created using square brackets: for example
a=[1,2,3]
Tuples are created using round brackets: for example
a=(1,2,3)
items are ordered, allow duplicate values. List items are changeable, whereas; Tuple items are unchangeable. items are indexed, the first item has index [0], the second item has index [1] etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 41 / 118

Lists, Tuples, Sets, Dictionaries
LISTS, TUPLES
are used to store multiple items in a single variable.
Lists are created using square brackets: for example
a=[1,2,3]
Tuples are created using round brackets: for example
a=(1,2,3)
items are ordered, allow duplicate values. List items are changeable, whereas; Tuple items are unchangeable. items are indexed, the first item has index [0], the second item has index [1] etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 41 / 118

Lists, Tuples, Sets, Dictionaries
LISTS, TUPLES
are used to store multiple items in a single variable.
Lists are created using square brackets: for example
a=[1,2,3]
Tuples are created using round brackets: for example
a=(1,2,3)
items are ordered, allow duplicate values. List items are changeable, whereas; Tuple items are unchangeable. items are indexed, the first item has index [0], the second item has index [1] etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 41 / 118

Lists, Tuples, Sets, Dictionaries
LISTS, TUPLES
are used to store multiple items in a single variable.
Lists are created using square brackets: for example
a=[1,2,3]
Tuples are created using round brackets: for example
a=(1,2,3)
items are ordered, allow duplicate values. List items are changeable, whereas; Tuple items are unchangeable. items are indexed, the first item has index [0], the second item has index [1] etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 41 / 118

Lists, Tuples, Sets, Dictionaries
LISTS, TUPLES
are used to store multiple items in a single variable.
Lists are created using square brackets: for example
a=[1,2,3]
Tuples are created using round brackets: for example
a=(1,2,3)
items are ordered, allow duplicate values. List items are changeable, whereas; Tuple items are unchangeable. items are indexed, the first item has index [0], the second item has index [1] etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 41 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list. The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Since lists/tuples are indexed, lists can have items with the same value. List/tuple items can be of any data type. A list/tuple can contain different data types
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 42 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
len() function is used to find the number of items in the list/tuple
list(())/tuple(()) constructor can be used to create a list/tuple List/tuple items are indexed and can be accessed them by referring to the index
number. The first item has index 0.
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 43 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
len() function is used to find the number of items in the list/tuple
list(())/tuple(()) constructor can be used to create a list/tuple List/tuple items are indexed and can be accessed them by referring to the index
number. The first item has index 0.
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 43 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
len() function is used to find the number of items in the list/tuple
list(())/tuple(()) constructor can be used to create a list/tuple List/tuple items are indexed and can be accessed them by referring to the index
number. The first item has index 0.
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 43 / 118

Lists, Tuples, Sets, Dictionaries
LISTS(CONTD...)
len() function is used to find the number of items in the list/tuple
list(())/tuple(()) constructor can be used to create a list/tuple List/tuple items are indexed and can be accessed them by referring to the index
number. The first item has index 0.
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 43 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
insert() is used to insert an item to the list
append() is used to add an item to the end of the list extend() is used to append elements from another list to the current list remove() used to remove specified item. pop() used to remove specified indes. del / clear() is used to delete the complete list. sort() is used to sort the items in the list.These functions can be used for a list. Tuple items cannot be changed using any of the
above. First, convert tuple to a list, apply changes and then again convert list to tuple.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 44 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
SETS
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items do not allow duplicate values. Once a set is created, one cannot change its items, but can add new items. A set can contain different data types set() constructor can be used to make a set.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 45 / 118

Lists, Tuples, Sets, Dictionaries
EXERCISE:
Type the following statements and observe the output:
>>> a=[23 ,46 ,56 ,21 ,13]
>>> a
>>> len ( a )
>>> a [ 0 ] , a [ 1 ] , a [ 5 ]
>>> a [ 6 ]
>>> a [ −1]
>>> a [ −4]
>>> a . append (23)
>>> a
>>> b=[78 ,58 ,74]
>>> a . append ( b )
>>> a
>>> a . append ( b [ 2 ] )
>>> a
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 46 / 118

Lists, Tuples, Sets, Dictionaries
EXERCISE:
Type the following statements and observe the output:
>>> a . i n s e r t (4 ,34)
>>> a
>>> a . i n s e r t (0 ,87)
>>> a
>>> a . pop ( )
>>> a
>>> a . pop ( 2 )
>>> a
>>> a . pop( −1)
>>> a
>>> a . remove (34)
>>> a
>>> a . remove ( a [ 2 ] )
>>> a
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 47 / 118

Lists, Tuples, Sets, Dictionaries
EXERCISE:
Type the following statements and observe the output:
>>> a =[12 ,36 ,9 ,23 ,8 ,5 ,3]
>>> a
>>> a . s o r t ( )
>>> a
>>> b=(12 ,36 ,9 ,23 ,8 ,5 ,3)
>>> b
>>> len ( b )
>>> c= l i s t ( b )
>>> c
>>> c . s o r t ( )
>>> c
>>> c . s o r t ( reverse=True )
>>> c
>>> b= t u p l e ( c )
>>> c . c l e a r ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 48 / 118

Lists, Tuples, Sets, Dictionaries
EXERCISE:
Type the following statements and observe the output:
>>> a={3 ,12 ,36 ,9 ,23 ,8 ,5 ,3}
>>> a
>>> b=set ([12 ,16 ,19 ,25 ,35 ,36 ,39])
>>> b
>>> c=a . union ( b )
>>> c
>>> d=a . i n t e r s e c t i o n ( b )
>>> d
>>> e=a . symmetric_difference ( b )
>>> e
>>> e . c l e a r ( )
>>> e
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 49 / 118

Lists, Tuples, Sets, Dictionaries
EXERCISE:
Type the following statements and observe the output:
>>> a={3 ,12 ,36 ,9 ,23 ,8 ,5 ,3}
>>> c=a . copy ( )
>>> b={3 ,56 ,23}
>>> d=a . d i f f e r e n c e ( b )
>>> c=a . union ( b )
>>> a . i s d i s j o i n t ( b )
>>> a . issubset ( b )
>>> a . remove ( 3 )
>>> a
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 50 / 118

Input and output statements
INPUT STATEMENT
Theinput()function allows user input.
SYNTAX:
input(prompt)
prompt– A String, representing a default message before the input.
For example:
x = i n p u t ( ’ Enter your name : ’ )
p r i n t ( ’ Hello , ’ +x )
p r i n t ( ’ Hello , ’ , x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 51 / 118

Input and output statements
OUTPUT STATEMENTS
Python provides theprint()function to display output to the standard output devices.
SYNTAX:
print(value(s),sep= ’ ’, end = ‘’, file=file, flush=flush)
value(s)– Any value, and as many as you like. Will be converted to string before printed
sep=‘separator’ – (Optional) Specify how to separate the objects, if there is more than
one. Default :’ ’
end=‘end’ – (Optional) Specify what to print at the end.Default : ‘’
file– (Optional) An object with a write method. Default :sys.stdout
flush– (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 52 / 118

Input and output statements
EXAMPLES FOR PRINT ()
Type the following commands and note the difference in output:
CODES:
p r i n t ( "REVA" )
p r i n t ( ’R’ , ’E’ , ’V’ , ’A ’ )
p r i n t ( "REVA" , end = "@" )
p r i n t ( ’R’ , ’E’ , ’V’ , ’A’ , sep ="#")
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 53 / 118

Input and output statements
FORMATTING OUTPUT
CODE1:
name = "REVA"
p r i n t ( f ’ Welcome to {name } ! ’ )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 54 / 118

Input and output statements
CODE2:
a = 20
b = 10
# a d d i t i o n
sum = a + b
# s u b t r a c t i o n
sub = a− b
# Output
p r i n t ( ’ The value of a i s { } and b i s { } ’ . format ( a , b ) )
p r i n t ( ’ { 2 } i s the sum of { 0 } and { 1 } ’ . format ( a , b , sum ) )
p r i n t ( ’ { sub_value } i s the s u b t r a c t i o n of { value_a } and { value_b } ’
. format ( value_a = a , value_b = b , sub_value =sub ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 55 / 118

Input and output statements
USING% OPERATOR
We can use ‘%’ operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 56 / 118

Input and output statements
EXAMPLE
CODE
# Taking i n p u t from the user
num = i n t ( i n p u t ( " Enter a value : " ) )
add = num + 5
# Output
p r i n t ( " The sum i s %d " %add )
CODE:
x = 12.3456789
p r i n t ( ’ The value of x i s %3.2f ’ %x )
p r i n t ( ’ The value of x i s %3.4f ’ %x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 57 / 118

Input and output statements
EXAMPLE
CODE
# Taking i n p u t from the user
num = i n t ( i n p u t ( " Enter a value : " ) )
add = num + 5
# Output
p r i n t ( " The sum i s %d " %add )
CODE:
x = 12.3456789
p r i n t ( ’ The value of x i s %3.2f ’ %x )
p r i n t ( ’ The value of x i s %3.4f ’ %x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 57 / 118

Input and output statements
EXAMPLE
CODE:
f o r x i n range (1 , 11):
p r i n t ( ’ { 0 : 2 d } {1:3 d } {2:4 d } ’ . format ( x , x
*
x , x
*
x
*
x ) )
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . r j u s t ( 2 ) , repr ( x
*
x ) . r j u s t ( 3 ) , end= ’ ’ )
# Note use of ’ end ’ on previous l i n e
p r i n t ( repr ( x
*
x
*
x ) . r j u s t ( 4 ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 58 / 118

Input and output statements
EXAMPLE
CODE:
f o r x i n range (1 , 11):
p r i n t ( ’ { 0 : 2 d } {1:3 d } {2:4 d } ’ . format ( x , x
*
x , x
*
x
*
x ) )
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . r j u s t ( 2 ) , repr ( x
*
x ) . r j u s t ( 3 ) , end= ’ ’ )
# Note use of ’ end ’ on previous l i n e
p r i n t ( repr ( x
*
x
*
x ) . r j u s t ( 4 ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 58 / 118

Input and output statements
EXAMPLE
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . l j u s t ( 2 ) , repr ( x
*
x ) . l j u s t ( 3 ) , end= ’ ’ )
p r i n t ( repr ( x
*
x
*
x ) . l j u s t ( 4 ) )
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . center ( 3 ) , repr ( x
*
x ) . center ( 6 ) , end= ’ ’ )
p r i n t ( repr ( x
*
x
*
x ) . center ( 6 ) )
Observe the difference in the output.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 59 / 118

Input and output statements
EXAMPLE
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . l j u s t ( 2 ) , repr ( x
*
x ) . l j u s t ( 3 ) , end= ’ ’ )
p r i n t ( repr ( x
*
x
*
x ) . l j u s t ( 4 ) )
CODE:
f o r x i n range (1 , 11):
p r i n t ( repr ( x ) . center ( 3 ) , repr ( x
*
x ) . center ( 6 ) , end= ’ ’ )
p r i n t ( repr ( x
*
x
*
x ) . center ( 6 ) )
Observe the difference in the output.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 59 / 118

Input and output statements
EXERCISES:
Read a list of elements using input function
Read a set from user input
Print the type of variable which were read in previous two commands
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 60 / 118

Conditional Statements
CONDITIONAL STATEMENTS
The basic tool of Control-flow statements isifstatement. Different variants of this are:
ifstatement – for implementing One-way branching
if-elsestatement – for implementing Two-way branching
elifstatement – for implementing Multiple branching
Nestedif-elsestatement – for implementing Multiple branching
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 61 / 118

Conditional Statements
IF
SYNTAX:
if condition:
Statements
Here condition is a boolean expression which gives either True or False.
Statements may be one or more statements to be executed.
EXAMPLE:
a= i n t ( i n p u t ( " Enter an i n t e g e r : " ) )
i f a>0:
p r i n t ( " Entered value i s p o s i t i v e " )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 62 / 118

Conditional Statements
IF
SYNTAX:
if condition:
Statements
Here condition is a boolean expression which gives either True or False.
Statements may be one or more statements to be executed.
EXAMPLE:
a= i n t ( i n p u t ( " Enter an i n t e g e r : " ) )
i f a>0:
p r i n t ( " Entered value i s p o s i t i v e " )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 62 / 118

Conditional Statements
IF-ELSE
SYNTAX:
if condition:
Statements 1
else:
Statements 2
If condition is True - Statements 1 will be executed.
otherwise - Statements 2 will be executed.
EXAMPLE:
a= i n t ( i n p u t ( " Enter an i n t e g e r : " ) )
i f a>0:
p r i n t ( " Entered value i s p o s i t i v e " )
else :
p r i n t ( " Entered value i s negative " )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 63 / 118

Conditional Statements
IF-ELSE
SYNTAX:
if condition:
Statements 1
else:
Statements 2
If condition is True - Statements 1 will be executed.
otherwise - Statements 2 will be executed.
EXAMPLE:
a= i n t ( i n p u t ( " Enter an i n t e g e r : " ) )
i f a>0:
p r i n t ( " Entered value i s p o s i t i v e " )
else :
p r i n t ( " Entered value i s negative " )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 63 / 118

Conditional Statements
ELIF
SYNTAX:
if condition 1:
Statements 1
elif condition 2:
Statements 2
elif condition 3:
Statements 3
else:
Statements 4
If condition 1 is True - Statements 1 will be executed.
else if condition 2 is True - Statements 2 will be executed and so on.
If any of the conditions is not True then statements in else block is executed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 64 / 118

Conditional Statements
EXAMPLE
EXAMPLE:
perc= f l o a t ( i n p u t ( " Enter the percentage of marks obtained by a
student : " ) )
i f perc >= 75:
p r i n t ( perc , ’ % − Grade : D i s t i n c t i o n ’ )
e l i f perc >= 60:
p r i n t ( perc , ’ % − Grade : F i r s t class ’ )
e l i f perc >=50:
p r i n t ( perc , ’ % − Grade : Second class ’ )
else :
p r i n t ( perc , ’ % − Grade : Fail ’ )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 65 / 118

Looping
WHILE
EXAMPLE:
i =1 # I n i t i a l i z a t i o n
while i <6: # t e s t c o n d i t i o n
p r i n t ( i )
i +=1 # increment or decrement
p r i n t ( ’ Task completed ’ )
EXAMPLE: USE OFbreakSTATEMENT
i = 1
while i < 6:
p r i n t ( i )
i f i == 3:
break
i += 1
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 66 / 118

Looping
WHILE
EXAMPLE:
i =1 # I n i t i a l i z a t i o n
while i <6: # t e s t c o n d i t i o n
p r i n t ( i )
i +=1 # increment or decrement
p r i n t ( ’ Task completed ’ )
EXAMPLE: USE OFbreakSTATEMENT
i = 1
while i < 6:
p r i n t ( i )
i f i == 3:
break
i += 1
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 66 / 118

Looping
EXAMPLE: USE OFcontinueSTATEMENT
i = 0
while i < 6:
i += 1
i f i == 3:
continue
p r i n t ( i )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 67 / 118

Looping
FOR
f o r <loop v a r i a b l e > i n sequence :
<statement 1>
<statement 2>
. . .
<statement n>
forstatement iterates over the members of a sequence in order, executing the block each
time
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 68 / 118

Looping
EXAMPLE:
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n f r u i t s :
p r i n t ( x )
Here x is the loop variable and the fruits here is the sequence.
f o r x i n " banana " :
p r i n t ( x )
In this example x is the loop variable and the sequence here is the string "banana".
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 69 / 118

Looping
EXAMPLE:
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n f r u i t s :
p r i n t ( x )
Here x is the loop variable and the fruits here is the sequence.
f o r x i n " banana " :
p r i n t ( x )
In this example x is the loop variable and the sequence here is the string "banana".
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 69 / 118

Looping
EXAMPLE:
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n f r u i t s :
p r i n t ( x )
Here x is the loop variable and the fruits here is the sequence.
f o r x i n " banana " :
p r i n t ( x )
In this example x is the loop variable and the sequence here is the string "banana".
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 69 / 118

Looping
EXAMPLE:
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n f r u i t s :
p r i n t ( x )
Here x is the loop variable and the fruits here is the sequence.
f o r x i n " banana " :
p r i n t ( x )
In this example x is the loop variable and the sequence here is the string "banana".
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 69 / 118

Looping
THE RANGE()FUNCTION
Generates a list of integers
SYNTAX:
range([start,] stop[, step])
EXAMPLE:
−−> range ( 6 )
This generates the values from 0 to 5 but not 6.
−−> range (1 ,50 ,5)
This generates the values from 1 to 49 with step of 5.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 70 / 118

Looping
THE RANGE()FUNCTION
Generates a list of integers
SYNTAX:
range([start,] stop[, step])
EXAMPLE:
−−> range ( 6 )
This generates the values from 0 to 5 but not 6.
−−> range (1 ,50 ,5)
This generates the values from 1 to 49 with step of 5.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 70 / 118

Looping
THE RANGE()FUNCTION
Generates a list of integers
SYNTAX:
range([start,] stop[, step])
EXAMPLE:
−−> range ( 6 )
This generates the values from 0 to 5 but not 6.
−−> range (1 ,50 ,5)
This generates the values from 1 to 49 with step of 5.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 70 / 118

Looping
THE RANGE()FUNCTION
Generates a list of integers
SYNTAX:
range([start,] stop[, step])
EXAMPLE:
−−> range ( 6 )
This generates the values from 0 to 5 but not 6.
−−> range (1 ,50 ,5)
This generates the values from 1 to 49 with step of 5.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 70 / 118

Looping
RANGE()FUNCTION(CONTD...)
To loop through a set of code a specified number of times, we can use therange()
function,
Therange()function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
EXAMPLE:
f o r x i n range ( 6 ) :
p r i n t ( x )
Hererange(6)is the values from 0 to 5 but not 6.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 71 / 118

Looping
RANGE()FUNCTION(CONTD...)
To loop through a set of code a specified number of times, we can use therange()
function,
Therange()function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
EXAMPLE:
f o r x i n range ( 6 ) :
p r i n t ( x )
Hererange(6)is the values from 0 to 5 but not 6.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 71 / 118

Looping
RANGE()FUNCTION(CONTD...)
To loop through a set of code a specified number of times, we can use therange()
function,
Therange()function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
EXAMPLE:
f o r x i n range ( 6 ) :
p r i n t ( x )
Hererange(6)is the values from 0 to 5 but not 6.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 71 / 118

Looping
RANGE()FUNCTION(CONTD...)
To loop through a set of code a specified number of times, we can use therange()
function,
Therange()function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
EXAMPLE:
f o r x i n range ( 6 ) :
p r i n t ( x )
Hererange(6)is the values from 0 to 5 but not 6.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 71 / 118

Looping
THE RANGE()FUNCTION(CONTD...)
Therange()function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter:range(2, 6), which means values from 2 to 6 (but not
including 6):
f o r x i n range ( 2 , 6 ) :
p r i n t ( x )
Therange()function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
f o r x i n range (2 , 30 , 3 ) :
p r i n t ( x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 72 / 118

Looping
THE RANGE()FUNCTION(CONTD...)
Therange()function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter:range(2, 6), which means values from 2 to 6 (but not
including 6):
f o r x i n range ( 2 , 6 ) :
p r i n t ( x )
Therange()function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
f o r x i n range (2 , 30 , 3 ) :
p r i n t ( x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 72 / 118

Looping
THE RANGE()FUNCTION(CONTD...)
Therange()function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter:range(2, 6), which means values from 2 to 6 (but not
including 6):
f o r x i n range ( 2 , 6 ) :
p r i n t ( x )
Therange()function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
f o r x i n range (2 , 30 , 3 ) :
p r i n t ( x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 72 / 118

Looping
THE RANGE()FUNCTION(CONTD...)
Therange()function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter:range(2, 6), which means values from 2 to 6 (but not
including 6):
f o r x i n range ( 2 , 6 ) :
p r i n t ( x )
Therange()function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
f o r x i n range (2 , 30 , 3 ) :
p r i n t ( x )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 72 / 118

Looping
NESTED LOOPS
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
adj = [ " red " , " big " , " t a s t y " ]
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n adj :
f o r y i n f r u i t s :
p r i n t ( x , y )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 73 / 118

Looping
NESTED LOOPS
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
adj = [ " red " , " big " , " t a s t y " ]
f r u i t s = [ " apple " , " banana " , " cherry " ]
f o r x i n adj :
f o r y i n f r u i t s :
p r i n t ( x , y )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 73 / 118

Looping
EXERCISES:
Sum of natural numbers using while loop
Finding the factors of a number using for loop
To check the given number is prime or not
Find the factorial of a number
To find largest of three numbers
Write a program to print even numbers between 25 and 45
Write a program to print all numbers divisible by 3 between 55 and 75
Write a program to print the first n Fibonacci numbers
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 74 / 118

Looping
SUM OF NATURAL NUMBERS USING WHILE LOOP
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
i , s=1 ,0
while i <=n :
s=s+ i
i = i +1
p r i n t ( ’ sum of f i r s t ’ , n , ’ n a t u r a l numbers = ’ , s )
FINDING THE FACTORS OF A NUMBER USING FOR LOOP
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p r i n t ( ’ The f a c t o r s of ’ , n , ’ are ’ )
f o r i i n range (1 , n +1):
i f n%i ==0:
p r i n t ( i , end= ’ ’ )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 75 / 118

Looping
SUM OF NATURAL NUMBERS USING WHILE LOOP
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
i , s=1 ,0
while i <=n :
s=s+ i
i = i +1
p r i n t ( ’ sum of f i r s t ’ , n , ’ n a t u r a l numbers = ’ , s )
FINDING THE FACTORS OF A NUMBER USING FOR LOOP
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p r i n t ( ’ The f a c t o r s of ’ , n , ’ are ’ )
f o r i i n range (1 , n +1):
i f n%i ==0:
p r i n t ( i , end= ’ ’ )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 75 / 118

Looping
TO CHECK THE GIVEN NUMBER IS PRIME OR NOT
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
f o r i i n range (2 , n ) :
i f n%i ==0:
p r i n t ( n , ’ i s not a prime ’ )
break
else :
p r i n t ( n , ’ i s a prime ’ )
FIND THE FACTORIAL OF A NUMBER
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p=1
f o r i i n range (1 , n +1):
p=p
*
i
p r i n t ( ’ f a c t o r i a l ( ’ , n , ’ ) = ’ , p )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 76 / 118

Looping
TO CHECK THE GIVEN NUMBER IS PRIME OR NOT
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
f o r i i n range (2 , n ) :
i f n%i ==0:
p r i n t ( n , ’ i s not a prime ’ )
break
else :
p r i n t ( n , ’ i s a prime ’ )
FIND THE FACTORIAL OF A NUMBER
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p=1
f o r i i n range (1 , n +1):
p=p
*
i
p r i n t ( ’ f a c t o r i a l ( ’ , n , ’ ) = ’ , p )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 76 / 118

Looping
TO FIND LARGEST OF THREE NUMBERS
def big ( a , b , c ) :
i f ( a>=b and a>=c ) :
p r i n t ( a , ’ i s bigger ’ )
e l i f ( b>=a and b>=c ) :
p r i n t ( b , ’ i s bigger ’ )
else :
p r i n t ( c , ’ i s bigger ’ )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 77 / 118

Function
FUNCTIONS INPYTHON
A function is a block of code that contains one or more Python statements and used
for performing a specific task.
Use of function:CODE RE-USABILITYWhile writing an application in Python, we may need to use a
specific code several times during coding. Assume that we need to write 25
lines of code to do a specific task.
Writing these 25 lines every time to perform the task is tedious, it would make
the code lengthy, less-readable and increase the chances of human errors.
It would be better to write these code in a function and just call the function
wherever needed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 78 / 118

Function
FUNCTIONS INPYTHON
A function is a block of code that contains one or more Python statements and used
for performing a specific task.
Use of function:CODE RE-USABILITYWhile writing an application in Python, we may need to use a
specific code several times during coding. Assume that we need to write 25
lines of code to do a specific task.
Writing these 25 lines every time to perform the task is tedious, it would make
the code lengthy, less-readable and increase the chances of human errors.
It would be better to write these code in a function and just call the function
wherever needed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 78 / 118

Function
FUNCTIONS INPYTHON
A function is a block of code that contains one or more Python statements and used
for performing a specific task.
Use of function:CODE RE-USABILITYWhile writing an application in Python, we may need to use a
specific code several times during coding. Assume that we need to write 25
lines of code to do a specific task.
Writing these 25 lines every time to perform the task is tedious, it would make
the code lengthy, less-readable and increase the chances of human errors.
It would be better to write these code in a function and just call the function
wherever needed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 78 / 118

Function
FUNCTIONS INPYTHON
A function is a block of code that contains one or more Python statements and used
for performing a specific task.
Use of function:CODE RE-USABILITYWhile writing an application in Python, we may need to use a
specific code several times during coding. Assume that we need to write 25
lines of code to do a specific task.
Writing these 25 lines every time to perform the task is tedious, it would make
the code lengthy, less-readable and increase the chances of human errors.
It would be better to write these code in a function and just call the function
wherever needed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 78 / 118

Function
FUNCTIONS INPYTHON
A function is a block of code that contains one or more Python statements and used
for performing a specific task.
Use of function:CODE RE-USABILITYWhile writing an application in Python, we may need to use a
specific code several times during coding. Assume that we need to write 25
lines of code to do a specific task.
Writing these 25 lines every time to perform the task is tedious, it would make
the code lengthy, less-readable and increase the chances of human errors.
It would be better to write these code in a function and just call the function
wherever needed.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 78 / 118

Function
IMPROVESREADABILITYBy using functions for frequent tasks one can make code
structured and readable. It would be easier for anyone to look at the code
and be able to understand the flow and purpose of the code.
AVOID REDUNDANCY When there is no repetition of code and use functions, one can
avoid the redundancy that may be created by not using functions.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 79 / 118

Function
IMPROVESREADABILITYBy using functions for frequent tasks one can make code
structured and readable. It would be easier for anyone to look at the code
and be able to understand the flow and purpose of the code.
AVOID REDUNDANCY When there is no repetition of code and use functions, one can
avoid the redundancy that may be created by not using functions.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 79 / 118

Function
SYNTAX
Function declaration:
def function_name ( function_parameters ) :
function_body # Set of Python statements
r e t u r n # o p t i o n a l r e t u r n statement
Calling the function:
v a r i a b l e = function_name ( parameters )
# v a r i a b l e i s to store the returned value
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 80 / 118

Function
SYNTAX
Function declaration:
def function_name ( function_parameters ) :
function_body # Set of Python statements
r e t u r n # o p t i o n a l r e t u r n statement
Calling the function:
v a r i a b l e = function_name ( parameters )
# v a r i a b l e i s to store the returned value
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 80 / 118

Function
EXAMPLE
def add (num1, num2 ) :
r e t u r n (num1+num2)
sum1=add (15 ,37)
sum2=add(345 ,9128)
p r i n t (sum1)
p r i n t (sum2)
p r i n t ( add (15 ,37))
p r i n t ( add (345 ,9128))
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 81 / 118

Function
EXAMPLE
Type the following command and observe the output
def add (num1, num2 ) :
r e t u r n (num1+num2)
p r i n t ( add (15 ,37))
p r i n t ( add (345))
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 82 / 118

Function
DEFAULT ARGUMENTS IN FUNCTION
By using default arguments one can avoid the errors that may arise while calling a
function without passing all the parameters.
def add (num1, num2=1):
r e t u r n (num1+num2)
p r i n t ( add (15 ,37))
p r i n t ( add (345))
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 83 / 118

Function
DEFAULT ARGUMENTS IN FUNCTION
By using default arguments one can avoid the errors that may arise while calling a
function without passing all the parameters.
def add (num1, num2=1):
r e t u r n (num1+num2)
p r i n t ( add (15 ,37))
p r i n t ( add (345))
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 83 / 118

Function
TYPES OF FUNCTIONS
There are two types of functions
1
Built-in functions:These functions are predefined in Python and we need not to
declare these functions before calling them. We can freely invoke them as and when
needed.
2
User defined functions:The functions which we create in our code are
user-defined functions.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 84 / 118

Function
RECURSIVE FUNCTION
A function is said to be a recursive if it calls itself.
def f a c t o r i a l (num ) :
i f num==1:
r e t u r n ( 1 )
else :
r e t u r n (num
*
f a c t o r i a l (num−1))
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p r i n t ( " F a c t o r i a l of " , n , " i s : " , f a c t o r i a l ( n ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 85 / 118

Function
RECURSIVE FUNCTION
A function is said to be a recursive if it calls itself.
def f a c t o r i a l (num ) :
i f num==1:
r e t u r n ( 1 )
else :
r e t u r n (num
*
f a c t o r i a l (num−1))
n= i n t ( i n p u t ( " Enter a n a t u r a l number : " ) )
p r i n t ( " F a c t o r i a l of " , n , " i s : " , f a c t o r i a l ( n ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 85 / 118

Function
BASE CASE IN RECURSION
When working with recursion, we should define a base case for which we already
know the answer.
Each successive recursive call to the function should bring it closer to the base case. We use base case in recursive function so that the function stops calling itself when
the base case is reached. Without the base case, the function would keep calling
itself indefinitely.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 86 / 118

Function
BASE CASE IN RECURSION
When working with recursion, we should define a base case for which we already
know the answer.
Each successive recursive call to the function should bring it closer to the base case. We use base case in recursive function so that the function stops calling itself when
the base case is reached. Without the base case, the function would keep calling
itself indefinitely.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 86 / 118

Function
BASE CASE IN RECURSION
When working with recursion, we should define a base case for which we already
know the answer.
Each successive recursive call to the function should bring it closer to the base case. We use base case in recursive function so that the function stops calling itself when
the base case is reached. Without the base case, the function would keep calling
itself indefinitely.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 86 / 118

Function
ADVANTAGES OF RECURSION
Easier to write.
Readable – Code is easier to read and understand.
Reduce the lines of code – It takes less lines of code to solve a problem using
recursion.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 87 / 118

Function
DISADVANTAGES OF RECURSION
Not all problems can be solved using recursion.
If we don’t define the base case then the code would run indefinitely.
Debugging is difficult in recursive functions as the function is calling itself in a loop
and it is hard to understand which call is causing the issue.
Memory overhead – Call to the recursive function is not memory efficient.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 88 / 118

math library
MATH LIBRARY
TRY TO EXECUTE THE FOLLOWING IN SHELL
>>> s q r t ( 5 )
>>> cos (90)
First we import the math module/library using the command
import math
This module provides access to the mathematical functions defined by the C
standard
These functions cannot be used with complex numbers.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 89 / 118

math library
MATH LIBRARY
TRY TO EXECUTE THE FOLLOWING IN SHELL
>>> s q r t ( 5 )
>>> cos (90)
First we import the math module/library using the command
import math
This module provides access to the mathematical functions defined by the C
standard
These functions cannot be used with complex numbers.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 89 / 118

math library
MATH LIBRARY
TRY TO EXECUTE THE FOLLOWING IN SHELL
>>> s q r t ( 5 )
>>> cos (90)
First we import the math module/library using the command
import math
This module provides access to the mathematical functions defined by the C
standard
These functions cannot be used with complex numbers.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 89 / 118

math library
FUNCTIONS IN MATH MODULE
ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x
comb(n,k) Evaluates to
n!
k!(n−k)!
whenk<=nand evaluates to zero whenk>n.
fabs(x) Return the absolute value of x.
factorial(x) Return x factorial as an integer.
floor(x) Return the floor of x, the largest integer less than or equal to x.
fsum(iterable) Return an accurate floating point sum of values in the iterable.
gcd(*integers) Return the greatest common divisor of the specified integer arguments.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 90 / 118

math library
FUNCTIONS IN MATH MODULE
lcm(*integers) Return the least common multiple of the specified integer arguments.
prod(iterable) Calculate the product of all the elements in the input iterable.
exp(x) Return e raised to the power x, where e = 2.718281. . . .
expm1(x) Return e raised to the power x, minus 1 i.e., (exp(x)-1).
log(x[, base]) With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base
log2(x) Return the base-2 logarithm of x.
log10(x) Return the base-10 logarithm of x
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 91 / 118

math library
FUNCTIONS IN MATH MODULE
sqrt(x) Return the square root of x.
isqrt(n) Return the integer square root of the nonnegative integer n.
acos(x) Return the arc cosine of x, in radians. The result is between 0 andπ.
asin(x) Return the arc sine of x, in radians. The result is between−π/2 andπ/2.
atan(x) Return the arc tangent of x, in radians. The result is between−π/2 andπ/2
atan2(y, x) Return atan(y / x), in radians. The result is between−πandπ
degrees(x) Convert angle x from radians to degrees.
radians(x) Convert angle x from degrees to radians.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 92 / 118

math library
FUNCTIONS IN MATH MODULE
cos(x) Return the cosine of x radians.
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
acosh(x) Return the inverse hyperbolic cosine of x.
asinh(x) Return the inverse hyperbolic sine of x.
atanh(x) Return the inverse hyperbolic tangent of x.
cosh(x) Return the hyperbolic cosine of x.
sinh(x) Return the hyperbolic sine of x.
tanh(x) Return the hyperbolic tangent of x.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 93 / 118

math library
FUNCTIONS IN MATH MODULE
pi The mathematical constantπ= 3.141592. . . , to available precision.
e The mathematical constant e = 2.718281. . . , to available precision.
tau The mathematical constantτ= 6.283185. . . , to available precision.
Tau is a circle constant equal to 2π.
inf A floating-point positive infinity.
nan A floating-point “not a number" (NaN) value.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 94 / 118

Using Numpy package
NUMPY PACKAGE
NumPy is a Python library.
NumPy is used for working with arrays. NumPy is short for “Numerical Python”. To start using numpy package we first import by using the following command
import numpy as np
the NumPy package can be referred to as np instead of numpy.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 95 / 118

Using Numpy package
NUMPY PACKAGE
NumPy is a Python library.
NumPy is used for working with arrays. NumPy is short for “Numerical Python”. To start using numpy package we first import by using the following command
import numpy as np
the NumPy package can be referred to as np instead of numpy.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 95 / 118

Using Numpy package
NUMPY PACKAGE
NumPy is a Python library.
NumPy is used for working with arrays. NumPy is short for “Numerical Python”. To start using numpy package we first import by using the following command
import numpy as np
the NumPy package can be referred to as np instead of numpy.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 95 / 118

Using Numpy package
NUMPY PACKAGE
NumPy is a Python library.
NumPy is used for working with arrays. NumPy is short for “Numerical Python”. To start using numpy package we first import by using the following command
import numpy as np
the NumPy package can be referred to as np instead of numpy.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 95 / 118

Using Numpy package
NUMPY PACKAGE
NumPy is a Python library.
NumPy is used for working with arrays. NumPy is short for “Numerical Python”. To start using numpy package we first import by using the following command
import numpy as np
the NumPy package can be referred to as np instead of numpy.
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 95 / 118

Using Numpy package
CREATING ARRAY
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 ] )
p r i n t ( a r r )
p r i n t ( type ( a r r ) )
0-DARRAY
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
import numpy as np
a r r = np . array (42)
p r i n t ( a r r )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 96 / 118

Using Numpy package
CREATING ARRAY
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 ] )
p r i n t ( a r r )
p r i n t ( type ( a r r ) )
0-DARRAY
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
import numpy as np
a r r = np . array (42)
p r i n t ( a r r )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 96 / 118

Using Numpy package
CREATING ARRAY
1-DARRAY
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 ] )
p r i n t ( a r r )
2-DARRAY
An array that has 1-D arrays as its elements is called a 2-D array. These are often used to
represent matrix or 2nd order tensors.
import numpy as np
a r r = np . array ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] )
p r i n t ( a r r )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 97 / 118

Using Numpy package
CREATING ARRAY
1-DARRAY
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 ] )
p r i n t ( a r r )
2-DARRAY
An array that has 1-D arrays as its elements is called a 2-D array. These are often used to
represent matrix or 2nd order tensors.
import numpy as np
a r r = np . array ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] )
p r i n t ( a r r )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 97 / 118

Using Numpy package
CREATING ARRAY
3-DARRAY
An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are
often used to represent a 3rd order tensor.
import numpy as np
a r r = np . array ( [ [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] , [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ] )
p r i n t ( a r r )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 98 / 118

Using Numpy package
CHECK DIMENSION OF ARRAY
TO CHECK THE DIMENSION
NumPy Arrays provides thendimattribute that returns an integer that tells us how many
dimensions the array have.
import numpy as np
a = np . array (42)
b = np . array ( [ 1 , 2 , 3 , 4 , 5 ] )
c = np . array ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] )
d = np . array ( [ [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] , [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ] )
p r i n t ( a . ndim )
p r i n t ( b . ndim )
p r i n t ( c . ndim )
p r i n t ( d . ndim )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 99 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN ARRAY
Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.
The indexes in NumPy arrays start with 0, meaning that the first element has index 0,
and the second has index 1 etc.
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 ] )
p r i n t ( a r r [ 1 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 100 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN ARRAY
Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.
The indexes in NumPy arrays start with 0, meaning that the first element has index 0,
and the second has index 1 etc.
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 ] )
p r i n t ( a r r [ 1 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 100 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN 2-DARRAY
To access elements from 2-D arrays we can use comma separated integers representing
the dimension and the index of the element.
EXAMPLE
import numpy as np
a r r = np . array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 0 ] ] )
p r i n t ( ’ 2 nd element on 1 s t row : ’ , a r r [ 0 , 1 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 101 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN 2-DARRAY
To access elements from 2-D arrays we can use comma separated integers representing
the dimension and the index of the element.
EXAMPLE
import numpy as np
a r r = np . array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 0 ] ] )
p r i n t ( ’ 2 nd element on 1 s t row : ’ , a r r [ 0 , 1 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 101 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN 3-DARRAY
To access elements from 3-D arrays we can use comma separated integers representing
the dimension and the index of the element.
EXAMPLE
import numpy as np
a r r = np . array ( [ [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] , [ [ 7 , 8 , 9 ] , [ 1 0 , 11 , 1 2 ] ] ] )
p r i n t ( a r r [ 0 , 1 , 2 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 102 / 118

Using Numpy package
ACCESSING ELEMENTS OF AN 3-DARRAY
To access elements from 3-D arrays we can use comma separated integers representing
the dimension and the index of the element.
EXAMPLE
import numpy as np
a r r = np . array ( [ [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] , [ [ 7 , 8 , 9 ] , [ 1 0 , 11 , 1 2 ] ] ] )
p r i n t ( a r r [ 0 , 1 , 2 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 102 / 118

Using Numpy package
SLICING ARRAY
Slicing in python means taking elements from one given index to another given index.
We
pass slice instead of index like this:[start:end]or[start:end:step].
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] )
p r i n t ( a r r [ 1 : 5 ] )
p r i n t ( a r r [ : 4 ] )
p r i n t ( a r r [ 1 : 5 : 2 ] )
p r i n t ( a r r [ : : 2 ] )
# f o r 2−D array
arr1 = np . array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 0 ] ] )
p r i n t ( arr1 [ 1 , 1 : 4 ] )
p r i n t ( arr1 [ 0 : 2 , 2 ] )
p r i n t ( arr1 [ 0 : 2 , 1 : 4 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 103 / 118

Using Numpy package
SLICING ARRAY
Slicing in python means taking elements from one given index to another given index.
We
pass slice instead of index like this:[start:end]or[start:end:step].
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] )
p r i n t ( a r r [ 1 : 5 ] )
p r i n t ( a r r [ : 4 ] )
p r i n t ( a r r [ 1 : 5 : 2 ] )
p r i n t ( a r r [ : : 2 ] )
# f o r 2−D array
arr1 = np . array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 0 ] ] )
p r i n t ( arr1 [ 1 , 1 : 4 ] )
p r i n t ( arr1 [ 0 : 2 , 2 ] )
p r i n t ( arr1 [ 0 : 2 , 1 : 4 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 103 / 118

Using Numpy package
SLICING ARRAY
Slicing in python means taking elements from one given index to another given index.
We
pass slice instead of index like this:[start:end]or[start:end:step].
EXAMPLE
import numpy as np
a r r = np . array ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] )
p r i n t ( a r r [ 1 : 5 ] )
p r i n t ( a r r [ : 4 ] )
p r i n t ( a r r [ 1 : 5 : 2 ] )
p r i n t ( a r r [ : : 2 ] )
# f o r 2−D array
arr1 = np . array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 0 ] ] )
p r i n t ( arr1 [ 1 , 1 : 4 ] )
p r i n t ( arr1 [ 0 : 2 , 2 ] )
p r i n t ( arr1 [ 0 : 2 , 1 : 4 ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 103 / 118

Using Numpy package
SOME ATTRIBUTES
shapereturns a tuple with each index having the number of corresponding elements.
import numpy as np
a r r = np . array ( [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] )
p r i n t ( a r r . shape )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 104 / 118

Using Sympy package
SYMPY PACKAGE
Symbolic computation deals with the computation of mathematical objects symbolically.
CONSIDER THE FOLLOWING EXAMPLE :
import math
math . s q r t ( 9 )
math . s q r t ( 8 )
import sympy
sympy . s q r t ( 3 )
sympy . s q r t ( 8 )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 105 / 118

Using Sympy package
SYMPY PACKAGE
Symbolic computation deals with the computation of mathematical objects symbolically.
CONSIDER THE FOLLOWING EXAMPLE :
import math
math . s q r t ( 9 )
math . s q r t ( 8 )
import sympy
sympy . s q r t ( 3 )
sympy . s q r t ( 8 )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 105 / 118

Using Sympy package
SYMPY PACKAGE
Symbolic computation deals with the computation of mathematical objects symbolically.
CONSIDER THE FOLLOWING EXAMPLE :
import math
math . s q r t ( 9 )
math . s q r t ( 8 )
import sympy
sympy . s q r t ( 3 )
sympy . s q r t ( 8 )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 105 / 118

Using Sympy package
SYMPY PACKAGE
CONSIDER THE FOLLOWING EXAMPLE :
a = ( x + 1)
**
2
b = x
**
2 + 2
*
x + 1
p r i n t ( s i m p l i f y ( a − b ) )
p r i n t ( i s ( a==b ) )
c = x
**
2 − 2
*
x + 1
p r i n t ( s i m p l i f y ( a − c ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 106 / 118

Using Sympy package
SYMPY PACKAGE
CONSIDER THE FOLLOWING EXAMPLE :
a = ( x + 1)
**
2
b = x
**
2 + 2
*
x + 1
p r i n t ( s i m p l i f y ( a − b ) )
p r i n t ( i s ( a==b ) )
c = x
**
2 − 2
*
x + 1
p r i n t ( s i m p l i f y ( a − c ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 106 / 118

Dictionary
DICTIONARY
Dictionaries are used to store data values inkey:valuepairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates. Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 107 / 118

Dictionary
DICTIONARY
Dictionaries are used to store data values inkey:valuepairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates. Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 107 / 118

Dictionary
DICTIONARY
Dictionaries are used to store data values inkey:valuepairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates. Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 107 / 118

Dictionary
DICTIONARY ITEMS
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented inkey:valuepairs, and can be referred to by using the
key name.
Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t [ " brand " ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 108 / 118

Dictionary
DICTIONARY ITEMS
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented inkey:valuepairs, and can be referred to by using the
key name.
Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t [ " brand " ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 108 / 118

Dictionary
DICTIONARY ITEMS
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented inkey:valuepairs, and can be referred to by using the
key name.
Example
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
p r i n t ( t h i s d i c t [ " brand " ] )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 108 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
DICTIONARY
Ordered or unordered
As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the samekey:
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013 ,
" year " : 2012
}
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 109 / 118

Dictionary
Dictionary Length:
To determine how many items a dictionary has, use the len()
function.
len ( t h i s d i c t )
Dictionary Items - Data Types
The values in dictionary items can be of any data
type.
p r i n t ( type ( t h i s d i c t ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 110 / 118

Dictionary
Dictionary Length:
To determine how many items a dictionary has, use the len()
function.
len ( t h i s d i c t )
Dictionary Items - Data Types
The values in dictionary items can be of any data
type.
p r i n t ( type ( t h i s d i c t ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 110 / 118

Dictionary
Dictionary Length:
To determine how many items a dictionary has, use the len()
function.
len ( t h i s d i c t )
Dictionary Items - Data Types
The values in dictionary items can be of any data
type.
p r i n t ( type ( t h i s d i c t ) )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 110 / 118

Dictionary
ACCESSINGITEMS
You can access the items of a dictionary by referring to its key name, inside square
brackets
x= t h i s d i c t [ " model " ]
There is also a method calledget()that will give you the same result.
x = t h i s d i c t . get ( " model " )
Get KeysThekeys()method will return a list of all the keys in the dictionary.
x = t h i s d i c t . keys ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 111 / 118

Dictionary
ACCESSINGITEMS
You can access the items of a dictionary by referring to its key name, inside square
brackets
x= t h i s d i c t [ " model " ]
There is also a method calledget()that will give you the same result.
x = t h i s d i c t . get ( " model " )
Get KeysThekeys()method will return a list of all the keys in the dictionary.
x = t h i s d i c t . keys ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 111 / 118

Dictionary
ACCESSINGITEMS
You can access the items of a dictionary by referring to its key name, inside square
brackets
x= t h i s d i c t [ " model " ]
There is also a method calledget()that will give you the same result.
x = t h i s d i c t . get ( " model " )
Get KeysThekeys()method will return a list of all the keys in the dictionary.
x = t h i s d i c t . keys ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 111 / 118

Dictionary
Get ValuesThevalues()method will return a list of all the values in the dictionary.
x = t h i s d i c t . values ( )
The list of the values/keys is aviewof the dictionary, meaning that any changes done
to the dictionary will be reflected in the values/keys list.
Get ItemsTheitems()method will return each item in a dictionary, as tuples in a list.
x = t h i s d i c t . items ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 112 / 118

Dictionary
Get ValuesThevalues()method will return a list of all the values in the dictionary.
x = t h i s d i c t . values ( )
The list of the values/keys is aviewof the dictionary, meaning that any changes done
to the dictionary will be reflected in the values/keys list.
Get ItemsTheitems()method will return each item in a dictionary, as tuples in a list.
x = t h i s d i c t . items ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 112 / 118

Dictionary
Get ValuesThevalues()method will return a list of all the values in the dictionary.
x = t h i s d i c t . values ( )
The list of the values/keys is aviewof the dictionary, meaning that any changes done
to the dictionary will be reflected in the values/keys list.
Get ItemsTheitems()method will return each item in a dictionary, as tuples in a list.
x = t h i s d i c t . items ( )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 112 / 118

Dictionary
ADDING ITEMS
Adding an item to the dictionary is done by using a new index key and assigning a
value to it
t h i s d i c t [ " rank " ] = " Yes "
p r i n t ( t h i s d i c t )
Theupdate()method will update the dictionary with the items from a given argument.
If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object withkey:valuepairs.
t h i s d i c t . update ( { " rank " : " Yes " } )
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 113 / 118

Dictionary
ADDING ITEMS
Adding an item to the dictionary is done by using a new index key and assigning a
value to it
t h i s d i c t [ " rank " ] = " Yes "
p r i n t ( t h i s d i c t )
Theupdate()method will update the dictionary with the items from a given argument.
If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object withkey:valuepairs.
t h i s d i c t . update ( { " rank " : " Yes " } )
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 113 / 118

Dictionary
ADDING ITEMS
Adding an item to the dictionary is done by using a new index key and assigning a
value to it
t h i s d i c t [ " rank " ] = " Yes "
p r i n t ( t h i s d i c t )
Theupdate()method will update the dictionary with the items from a given argument.
If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object withkey:valuepairs.
t h i s d i c t . update ( { " rank " : " Yes " } )
p r i n t ( t h i s d i c t )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 113 / 118

Dictionary
COPYDICTIONARIES
One cannot copy a dictionary simply by typingdict2 = dict1, because:dict2will only
be a reference todict1, and changes made indict1will automatically also be made in
dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method
copy().
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
mydict= t h i s d i c t . copy ( )
p r i n t ( mydict )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 114 / 118

Dictionary
COPYDICTIONARIES
One cannot copy a dictionary simply by typingdict2 = dict1, because:dict2will only
be a reference todict1, and changes made indict1will automatically also be made in
dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method
copy().
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
mydict= t h i s d i c t . copy ( )
p r i n t ( mydict )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 114 / 118

Dictionary
COPYDICTIONARIES
One cannot copy a dictionary simply by typingdict2 = dict1, because:dict2will only
be a reference todict1, and changes made indict1will automatically also be made in
dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method
copy().
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
mydict= t h i s d i c t . copy ( )
p r i n t ( mydict )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 114 / 118

Dictionary
COPYDICTIONARIES
Another way to make a copy is to use the built-in functiondict().
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
mydict= d i c t ( t h i s d i c t )
p r i n t ( mydict )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 115 / 118

Dictionary
COPYDICTIONARIES
Another way to make a copy is to use the built-in functiondict().
t h i s d i c t = {
" brand " : "REVA" ,
" model " : " U n i v e r s i t y " ,
" year " : 2013
}
mydict= d i c t ( t h i s d i c t )
p r i n t ( mydict )
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 115 / 118

Dictionary
NESTEDDICTIONARIES
A dictionary can contain dictionaries, this is called nested dictionaries.
s t u d e n t _ l i s t = {
" std1 " : {
"name" : "ABC" ,
" year " : 2020
} ,
" std2 " : {
"name" : "XYZ" ,
" year " : 2021
}
}
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 116 / 118

Dictionary
NESTEDDICTIONARIES
A dictionary can contain dictionaries, this is called nested dictionaries.
s t u d e n t _ l i s t = {
" std1 " : {
"name" : "ABC" ,
" year " : 2020
} ,
" std2 " : {
"name" : "XYZ" ,
" year " : 2021
}
}
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 116 / 118

Dictionary
REMOVEDICTIONARY ITEMS
Thepop()method removes the item with the specified key name. For example
thisdict.pop("model")removes the item with keymodel.
Thepopitem()method removes the last inserted item. Thedelkeyword removes the item with the specified key name. For exampledel
thisdict["year"]
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 117 / 118

Dictionary
REMOVEDICTIONARY ITEMS
Thepop()method removes the item with the specified key name. For example
thisdict.pop("model")removes the item with keymodel.
Thepopitem()method removes the last inserted item. Thedelkeyword removes the item with the specified key name. For exampledel
thisdict["year"]
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 117 / 118

Dictionary
REMOVEDICTIONARY ITEMS
Thepop()method removes the item with the specified key name. For example
thisdict.pop("model")removes the item with keymodel.
Thepopitem()method removes the last inserted item. Thedelkeyword removes the item with the specified key name. For exampledel
thisdict["year"]
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 117 / 118

Dictionary
Thank You
K SUSHAN BAIRY (Reva University) PYTHON - An Introduction 118 / 118
Tags