Python Content Manual
Python Content Manual
Python Content Manual
ARTIFICIAL
INTELLIGENCE
CURRICULUM
Curated with support from Intel®
2
Acknowledgements
Patrons:
• Sh. Ramesh Pokhriyal 'Nishank', Minister of Human Resource Development,
Government of India
• Sh. Dhotre Sanjay Shamrao, Minister of State for Human Resource Development,
Government of India
Feedback By:
• Ms. Neelam Roy, ITL Public School, Delhi
• Ms. Mehreen Shamim, TGT, Delhi Public School – Bangalore East, Bengaluru
• Ms. Saswati Sarangi, PGT Computer Science, RCIS Kalyan Nagar, Bengaluru
• Ms. Isha, HOD Computer Science, Salwan Public School, Delhi
• Ms. Aayushi Agrawal, Salwan Girls School, Delhi
3
Special Thanks To:
• Ms. Indu Khetrapal, Principal, Salwan Public School, Delhi
• Ms. Rekha Vinod, Principal, RCIS Kalyan Nagar, Delhi
• Ms. Manilla Carvalho, Principal, Delhi Public School – Bangalore East, Bengaluru
• Ms. Sudha Acharya, Principal, ITL Public School, Delhi
• Ms. Puneet Sardana, Vice Principal, Salwan Girls School, Delhi
4
5
About the Book
Artificial Intelligence (AI) is being widely recognized to be the power that will fuel the future
global digital economy. AI in the past few years has gained geo-strategic importance and a
large number of countries are striving hard to stay ahead with their policy initiatives to get
their country ready.
India's own AI Strategy identifies AI as an opportunity and solution provider for inclusive
economic growth and social development. The report also identifies the importance of skills-
based education (as opposed to knowledge intensive education), and the value of project
related work in order to “effectively harness the potential of AI in a sustainable manner” and
to make India's next generation 'AI ready'.
CBSE is already offering various Skill subjects at Secondary and Senior Secondary level to
upgrade the skills and proficiency of the young generation and also to provide them
awareness to explore various career options. At Secondary Level, a Skill subject may be
offered as additional sixth subject along with the existing five compulsory subjects.
CBSE acknowledges the initiative by Intel India in curating this Python Content Manual, the
AI training video and managing the subsequent trainings of trainers on the Artificial
Intelligence Curriculum.
The aim is to strive together to make our students future ready and help them work on
incorporating Artificial Intelligence to improve their learning experience.
6
Contents
Acknowledgements ............................................................................................................... 3
About the Book ..................................................................................................................... 6
Chapter 1: Algorithms and Flowcharts ................................................................................ 10
Recap .............................................................................................................................. 10
Quiz Time! ................................................................................................................... 10
Introduction ..................................................................................................................... 14
What is an Algorithm? .................................................................................................. 15
Activity ......................................................................................................................... 15
Challenge Time ............................................................................................................ 16
What is a flowchart? ..................................................................................................... 18
How to Use Flowcharts to Represent Algorithms ......................................................... 19
Challenge time! ............................................................................................................... 20
Test Your Knowledge ...................................................................................................... 20
Chapter 2: Introduction to Python ........................................................................................ 21
What is a program?...................................................................................................... 21
What is Python? ........................................................................................................... 21
Why Python for AI? ...................................................................................................... 22
Applications of Python.................................................................................................. 22
Getting started with Python.............................................................................................. 23
Downloading and Setting up Python for use................................................................. 23
Python IDLE installation ............................................................................................... 23
Run in the Integrated Development Environment (IDE) ................................................... 29
Interactive Mode .......................................................................................................... 29
Script Mode.................................................................................................................. 30
Python Statement and Comments ................................................................................... 32
Python Statement ........................................................................................................ 32
Python Comments ....................................................................................................... 32
Python Keywords and Identifiers .................................................................................. 33
Variables and Datatypes .............................................................................................. 35
Python Operators I .......................................................................................................... 41
Arithmetic Operators .................................................................................................... 41
Python Input and Output .................................................................................................. 41
Python Output Using print() function ............................................................................ 41
User input .................................................................................................................... 42
Type Conversion ............................................................................................................. 42
7
Implicit Type Conversion .............................................................................................. 42
Explicit Type Conversion.............................................................................................. 44
Python Operators II ......................................................................................................... 47
Comparison operators.................................................................................................. 47
Logical operators ......................................................................................................... 47
Assignment operators .................................................................................................. 48
Let’s Practice ................................................................................................................... 48
Test Your Knowledge ...................................................................................................... 49
Chapter 3 - Introduction to tools for AI ................................................................................. 50
Recap .......................................................................................................................... 50
Introduction to Anaconda ................................................................................................. 50
How to install Anaconda?............................................................................................. 50
Jupyter Notebook ............................................................................................................ 56
Introduction .................................................................................................................. 56
What is a Notebook? .................................................................................................... 56
Installing Jupyter Notebook .......................................................................................... 57
Working with Jupyter Notebook.................................................................................... 57
Notebook Interface - Explained! ................................................................................... 58
Test Your Knowledge ...................................................................................................... 64
Chapter 4 - More About Lists and Tuples ............................................................................ 65
Introduction to Lists ......................................................................................................... 65
How to create a list ? ....................................................................................................... 65
How to access elements of a list ?................................................................................... 65
List Index ..................................................................................................................... 66
Negative Indexing ........................................................................................................ 66
Adding Element to a List .................................................................................................. 67
Using append() method................................................................................................ 67
Using insert() Method ................................................................................................... 68
Using extend() method ................................................................................................. 68
Removing Elements from a List ....................................................................................... 68
Using remove() method................................................................................................ 69
Using pop() method ..................................................................................................... 69
Slicing of a List ................................................................................................................ 70
List Methods ................................................................................................................ 72
Let’s Practice ................................................................................................................... 72
Introduction to Tuples ...................................................................................................... 72
8
How to Create a tuple ? ................................................................................................... 73
Accessing of Tuples ........................................................................................................ 73
Deleting a Tuple .............................................................................................................. 73
Test Your Knowledge ...................................................................................................... 74
Chapter 5 - Flow of Control and Conditions......................................................................... 75
If Statement ..................................................................................................................... 75
If Statement ................................................................................................................. 77
Python if...else Statement ............................................................................................ 78
Python if...elif...else Statement ..................................................................................... 79
Syntax of if...elif...else .................................................................................................. 79
Python Nested if statements ............................................................................................ 81
Let’s Practice ................................................................................................................... 81
The For Loop ................................................................................................................... 82
Syntax of for Loop ........................................................................................................ 82
Flowchart of for Loop ................................................................................................... 82
Example: Python for Loop ............................................................................................ 82
The while Statement ........................................................................................................ 83
Syntax of while Loop in Python .................................................................................... 83
Flowchart of while Loop ................................................................................................... 84
Example: Python while Loop ........................................................................................... 84
Let’s Practice ................................................................................................................... 85
Test Your Knowledge ...................................................................................................... 85
Chapter 6 : Introduction to Packages .................................................................................. 86
Recap .............................................................................................................................. 86
CHALLENGE TIME! ..................................................................................................... 86
Introduction ..................................................................................................................... 87
What is a package? ......................................................................................................... 90
Package Installation ..................................................................................................... 91
Working with a package ............................................................................................... 91
What is NumPy? .......................................................................................................... 92
Exploring NumPy! ........................................................................................................ 93
Let’s Practice! .................................................................................................................. 94
TASK 1 ........................................................................................................................ 94
TASK 2 ........................................................................................................................ 94
Test Your Knowledge ...................................................................................................... 94
Additional Resources .......................................................................................................... 95
9
Chapter 1: Algorithms and Flowcharts
Recap
Till now we have gone through an experiential learning around Artificial Intelligence in which
we got to know about so many new concepts like what is Artificial Intelligence, Machine
Learning, Deep learning, Rule-based approach, learning based approach, neural networks,
etc. Now, it is time to move ahead in this journey towards AI Readiness and work around the
concepts we are introduced to through hands-on learning sessions.
But before we start getting our hands dirty, let us recall what has been done so far. Here is a
quiz through which you can challenge yourself and see how well do you remember things.
Quiz Time!
1. Which stage is missing in AI Project Cycle?
10
3. What will be the output for this program?
11
7. Google Deep Mind AI is based on reinforcement learning.
12. Problem statement template does not talk about goal of the project?
14. Which of the following is commonly used for image processing in python?
12
15. Box plots help in finding out_______?
16. The AI domain which can be used to predict the Air Quality Index is?
13
What you Know?
Ever wondered how do people create such programs? Write your thoughts below.
14
To develop a program, the very first step that comes into the picture is to specify the
task which the machine needs to do. Once the task or the main objective of the
program is finalized, the task is broken into smaller tasks which altogether contribute
towards achieving the main goal. To make sure that the flow of the process is
proper, algorithms and flowcharts are used which help us into developing a stepwise
framework to achieve the main goal.
What is an Algorithm?
To write a logical step-by-step method to solve the identified problem is called
algorithm, in other words, an algorithm is a procedure for solving problems. In order
to solve a mathematical or computer problem, this is the first step of the procedure.
An algorithm includes calculations, reasoning and data processing. Algorithms can
be presented by natural languages, pseudocode and flowcharts, etc.
Activity
Goal: To give a glimpse of how to write a step by step algorithm for any
problem/process in a bidirectional manner.
15
• Take a pan and boil approx. 200 ml of water.
Step 1
• Stir constantly and cook in the open pan till the water is
Step 3 soaked by the noodles.
• Serve Hot.
Step 4
Can you think of other ways to make instant noodles? Write them down.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Challenge Time
Before we jump into challenging ourselves, let us go through some ground rules for
this activity:
16
Write algorithms for the challenges given.
Level
1
Making Tea/Coffee/Hot chocolate
Level
2
Make Chapati/Rice
Level
3
Make Samosa/Masala Dosa
Now, exchange your attempts with your friend and see what procedure have they
followed for the same tasks.
17
Yes! Write the differences below. No! How are they so similar?
Re-look at your own algorithms now. Do you wish to make any changes to it? Is
there a need to add/subtract step(s) in it? Take your time and make the necessary
changes if required.
1. How to divide a task into several sub-tasks and the advantage of doing so.
2. There can be multiple approaches in terms of the number of sub-tasks or the
methods used in sub-tasks to solve a problem and the one which is the
simplest and the most efficient should be chosen above all.
What is a flowchart?
A flowchart is the graphical or pictorial representation of an algorithm with the help of
different symbols, shapes and arrows in order to demonstrate a process or a
program. While computers work with numbers at ease, humans need visual
representations to understand the information well and communicate it effectively.
Thus, flowcharts are used to break a process into smaller parts and elaborate it
using visual representations.
Several standard graphics are applied in a flowchart:
18
Terminal Box Input / Output Process / Decision Connector /
(Start / End) Instruction Arrow
Now that we have the definitions of algorithm and flowchart, how do we use a
flowchart to represent an algorithm? Let us take a look at given examples and see
how they work.
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.
Flowchart:
19
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
ALGORITHM FLOWCHART
Step 3: Print C
Challenge time!
Let us practice what we have learnt so far. Write algorithms and draw flowcharts for
the tasks given below.
TASK 1: How to check whether the input number is prime or not?
TASK 2: How does a traffic signal work?
TASK 3: How to make an ATM transaction?
TASK 4: How to check if a light bulb is working or not?
TASK 5: How to win a Rock, Paper, Scissors Game – To know more about this game, go to
https://www.wikihow.com/Play-Rock,-Paper,-Scissors
20
Chapter 2: Introduction to Python
In the previous section, you learnt about the different methodologies for programming. A
programming language is a formal language that specifies a set of instructions that can be
used to produce various kinds of output.
In simple Words, a programming language is a vocabulary and set of grammatical rules for
instructing a computer to perform specific tasks. Though there are many different
programming languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc.
we will study Python in this course.
What is a program?
A computer program is a collection of instructions that perform a specific task when
executed by a computer. It is usually written by a computer program in a programming
language.
Before getting into understanding more about Python, we need to first understand what is
Python and why we need to use Python?
What is Python?
21
Why Python for AI?
Artificial intelligence is the trending technology of the future. You can see so many
applications around you. If you as an individual can also develop an AI application, you will
require to know a programming language. There are various programming languages like
Lisp, Prolog, C++, Java and Python, which can be used for developing applications of AI.
Out of these, Python gains a maximum popularity because of the following reasons:
Applications of Python
Python is used for a large number of applications. Some of them are mentioned below:
22
Web and
Internet
Developme
nt
Desktop Business
GUI Applications
Applications
Application of
Python
Database
Access
To write and run Python program, we need to have Python interpreter installed in our
computer.
23
CLICK ON
Next
CLICK ON
Browse
24
CLICK ON
C: Drive
CLICK ON
Make New Folder
ABC1
ABC2
ABC3
ABC4
ABC5
25
Name the Folder as
Python37
26
CLICK ON
OK
CLICK ON
Install
27
28
Run in the Integrated Development Environment (IDE)
When we install Python, an IDE named IDLE is also installed. We can use it to run Python
on our computer.
IDLE (GUI integrated) is the standard, most popular Python development environment. IDLE
is an acronym of Integrated Development Environment. It lets one edit, run, browse and
debug Python Programs from a single interface. This environment makes it easy to write
programs.
Python shell can be used in two ways, viz., interactive mode and script mode. Where
Interactive Mode, as the name suggests, allows us to interact with OS; script mode lets us
create and edit Python source file.
Interactive Mode
You can see the above example, Python IDLE Shell account has >>> as Python prompt,
where simple mathematical expressions and single line Python commands can be written
and can be executed simply by pressing enter.
The first expression 3+10 written on the first Python prompt shows 13 as output in the next
line.
The second expression 2+4*10 written on the second Python prompt shows 42 as output in
the next line.
The third statement print("Hello Learner") written on the third Python prompt shows Hello
Learner as output in the next line.
The third statement print("Result:", 40+5*100) written on the fourth Python prompt shows
Result: as output in the next line.
29
Try Yourself
Script Mode
In script mode, we type Python program in a file and then use the interpreter to execute the
content from the file. Working in interactive mode is convenient for beginners and for testing
small pieces of code, as we can test them immediately. But for coding more than few lines,
we should always save our code so that we may modify and reuse the code.
Note: Result produced by Interpreter in both the modes, viz., Interactive and script mode is
exactly the same.
In shell Mode,
Click File >> New File
To write a Python script/program, we need to open a new file - File >> New File, type a
sequence of Python statements for solving a problem, save it with a meaningful name - File
>> Save, and finally Run the program to view the output of the program.
30
Now, type your first Python Program
Code Explanation:
Line 1 in the above code starting with # is a comment line, which means the line is non-
executable and it is only for the programmer’s reference.
Hello
Line 4 will display Learner and will allow the next output to get displayed in the same line
Hello
Learner Sam
50 times 300 is 15000
31
Python Statement and Comments
In this section we will learn about Python statements, why indentation is important and how
to use comments in programming.
Python Statement
Instructions written in the source code for execution are called statements. There are
different types of statements in the Python programming language like Assignment
statement, Conditional statement, Looping statements etc. These help the user to get the
required output. For example, n = 50 is an assignment statement.
Multi-line statement
However, Statements in Python can be extended to one or more lines using parentheses (),
braces {}, square brackets [], semi-colon (;), continuation character slash (\). When we need
to do long calculations and cannot fit these statements into one line, we can make use of
these characters.
Examples:
Type of Multi-line Usage
Statement
Using Continuation s = 1 + 2 + 3 + \
Character (/) 4 + 5 + 6 + \
7 + 8 + 9
Using Parentheses () n = (1 * 2 * 3 + 4 – 5)
Python Comments
A comment is text that doesn't affect the outcome of a code, it is just a piece of text to let
someone know what you have done in a program or what is being done in a block of code.
32
Python Keywords and Identifiers
In this section, we will learn about keywords (reserved words in Python) and identifiers
(names given to variables, functions, etc.).
Keywords
33
The list of all the keywords is given below.
34
Note:
Python is a case-sensitive language. This means, Variable and variable are not the same.
Always name identifiers that make sense.
While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to
figure out what it does even when you look at your code after a long gap.
x = 42
y = 42
35
These declarations make sure that the program reserves memory for two variables with the
names x and y. The variable names stand for the memory location. It's like the two
shoeboxes, which you can see in the picture. These shoeboxes are labelled with x and y and
the corresponding values are stored in the shoeboxes. Like the two shoeboxes, the memory
is empty as well at the beginning.
Note:
Assignment operator is used in Python to assign values to variables. For example, a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
Examples on Variables:
36
print(c)
Constants:
Non technically, you can think of constant as a shoe box with a fixed size of shoe kept inside
which cannot be changed after that.
In Python, constants are usually declared and assigned on a module. Here, the module
means a new file containing variables, functions etc. which is imported to the main file.
Inside the module, constants are written in all capital letters and underscores separating the
words.
• Create a info.py
NAME = "Ajay"
AGE = 24
• Create a main.py
import info
print(info.NAME)
print(info.AGE)
Ajay
24
37
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import the constant
module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. The global or constants module is used
throughout the Python programs.
Use camelCase
Create a name that Use capital letters
notation to declare a
makes sense. where possible to
variable. It starts with
Suppose, vowel makes declare a constant. For
lowercase letter. For
more sense than v. example: PI
example: myName
Datatypes
Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are mentioned below in
the image
38
1) Python Numbers
Number data type stores Numerical Values. These are of three different types:
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99,
0, 17. While writing a large integer value, don’t use commas to separate digits. Also, integers
should not have leading zeros.
Floating Point:
Numbers with fractions or decimal point are called floating point numbers.
A floating-point number will consist of sign (+,-) sequence of decimals digits and a dot such
as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be used to represent a
number in engineering/ scientific notation.
2) None
This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
3) Sequence
a) Strings
b) Lists
c) Tuples
String
Lists
List is also a sequence of values of any type. Values in the list are called elements / items.
These are indexed/ordered. List is enclosed in square brackets.
Example:
39
dob = [19,"January",1990]
Tuples:
Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in ().
Example:
t = (5,'program',2.5)
4) Sets
Example:
>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}
5) Mapping
Dictionaries
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key: value. Key and value can be of any type.
Example
>>> d = {1:'Ajay','key':2}
>>> type(d)
<class 'dict'>
40
Python Operators I
Operators are special symbols which represent computation. They are applied on
operand(s), which can be values or variables. Same operators can behave differently on
different data types. Operators when applied on operands form an expression. Operators are
categorized as Arithmetic, Relational, Logical and Assignment. Value and variables when
used with operator are known as operands.
Arithmetic Operators
a = "Hello World!"
print(a)
Hello World!
print(15 + 35) 50
x = 1.3 x =
print("x = /n", x) 1.3
m = 6 I have 6 apples
print(" I have %d apples",m)
User input
In all the examples till now, we have been using the calculations on known values
(constants). Now let us learn to take user’s input in the program. In python, input() function is
used for the same purpose.
Syntax Meaning
<String Variable>=input(<String>) For string input
<integer Variable>=int(input(<String>)) For integer input
<float Variable>=float(input(<String>)) For float (Real no.) input
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.
42
Example:
principle_amount = 2000
roi = 4.5
time = 10
43
Example Sample Output Explanation
Code
a = 10 File "cbse2.py", line 3, in The output shows an
b = "Hello" <module> error which says that
print(a+b) print(a+b) we cannot add integer
TypeError: unsupported and string variable
operand type(s) for +: types using implicit
'int' and 'str' conversion
Try It Yourself:
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.
44
Syntax:
(required_datatype)(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example: Adding of string and an integer using explicit conversion
Birth_day = 10
Birth_month = "July"
Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))
In above program,
45
Example Code Sample Output Explanation
a = 20 20 Apples Writing str(a) will
b = "Apples" convert integer a
print(str(a)+ b) into a string and
then will add to
the string b.
Try it yourself:
1) Take a Boolean value “False” and a float number “15.6” and perform the AND
operation on both
2) Take a string “ Zero” and a Boolean value “ True” and try adding both by using the
Bool() function.
3) Take a string “Morning “ and the float value “90.4” and try and add both of them by
using the float() function.
Perform the above mentioned Try it Yourself in the lab and write down the observations to
be discussed later in the class.
Note:
There is no difference in single or double quoted string. Both representations can be used
interchangeably. However, if either single or double quote is a part of the string itself, then
the string must be placed in double or single quotes respectively.
46
Python Operators II
Comparison operators
Operator Meaning Expression Result
> Greater Than 20 > 10 True
15 > 25 False
< Less Than 20 < 45 True
20 < 10 False
== Equal To 5 == 5 True
5 == 6 False
!= Not Equal to 67 != 45 True
35 != 35 False
Comparison operators are used to compare values. It either returns True or False according
to the condition.
Logical operators
Operator Meaning Expression Result
And And operator True and True True
True and False False
Or Or operator True or False True
False or False False
Not Not Operator not False True
not True False
47
Assignment operators
Let’s Practice
INPUT
L=int(input("Length"))
B=int(input("Breadth"))
PROCESS
Area=L*B
Perimeter=2*(L+B)
OUTPUT
print("Area:",Area)
print("Perimeter:",Perimeter
)
Python Code Sample Output
# To calculate Area and Length:50
# Perimeter of a rectangle Breadth:20
L=int(input("Length")) Area:100
B=int(input("Breadth")) Perimeter:140
Area=L*B
Perimeter=2*(L+B)
print("Area:",Area)
print("Perimeter:",Perimeter)
48
Try writing your code Sample Output
# To calculate Area of a triangle Base:20
# with Base and Height Height:10
_________________ #Input Base Area:100
_________________ #Input Height
_________________ #Calculate Area
_________________ #Display Area
49
Chapter 3 - Introduction to tools for AI
Recap
Till now we have learnt about flowcharts & algorithms, Python programming language, and
how to run programs in IDLE, what are packages and modules, and how it helps us in better
and faster coding. Now, we will learn and explore new tools which will help us with better
understanding, faster debugging of codes, and a lot more.
Introduction to Anaconda
We have explored about 3 major domains of AI: Data, NLP and CV. It often happens that
while writing a code, these domains have different packages which need to be installed.
Though we can install them all in IDLE, it is difficult to manage them all.
Anaconda is a free and open-source distribution of the Python language for scientific
computing (data science, machine learning applications, large-scale data processing,
predictive analytics, etc.), that aims to simplify package management and deployment. It
provides the facility to create different virtual environments, each having its own packages
and settings, as per user’s need.
1) Log on to https://www.anaconda.com/distribution/
50
2) Scroll down to the bar with operating system options and click on windows.
51
3) Under Python 3.7 version, select the right option according to the configuration of
your pc(32-bit/64-bit). The download will begin.
52
9) Do not change anything in PATH Options, click “Next”.
10) Wait for the installation to complete.
11) Click on “Skip” to continue.
53
12) Click on “Finish”. Your Anaconda setup is complete!
You can also install anaconda for MacOS and Linux from
https://www.anaconda.com/distribution/
54
55
Note the (base) written at the beginning of the line, it shows that the active environment is
base, as it is the default environment.
Jupyter Notebook
https://www.dataquest.io/blog/jupyter-notebook-tutorial/
https://realpython.com/jupyter-notebook-introduction/
https://jupyter.readthedocs.io/en/latest/glossary.html#term-kernel
https://www.dataquest.io/blog/jupyter-notebook-tutorial/
Introduction
The Jupyter Notebook is an incredibly powerful tool for interactively developing and
presenting AI related projects. The Jupyter project is the successor to the earlier IPython
Notebook, which was first published as a prototype in 2010. Although it is possible to use
many different programming languages within Jupyter Notebooks, Python remains the most
commonly used language for it. In other words, we can say that the Jupyter Notebook is an
open source web application that you can use to create and share documents that contain
live code, equations, visualizations, and text.
What is a Notebook?
Before we dive deep into Jupyter Notebooks, let us first understand what a notebook is. A
notebook integrates code and its output into a single document that combines visualizations,
narrative text, mathematical equations, and other rich media. This intuitive workflow
promotes iterative and rapid development, making notebooks an increasingly popular choice
at the heart of contemporary data science, analysis, and increasingly science at large.
56
Installing Jupyter Notebook
The easiest way to install and start using Jupyter Notebook is through Anaconda. Anaconda
is the most widely used Python distribution for data science and comes pre-loaded with all
the most popular libraries and tools. With Anaconda, comes the Anaconda Navigator
through which we can scroll around all the applications which come along with it.
To install the kernel, Open Anaconda Prompt and execute the following command:
Here, Jupyter is an extension to the Jupyter Notebook which gets installed. Ipykernel is a
powerful and interactive Python shell and a jupyter kernel to work with python code in
Jupyter Notebooks and nb_conda refers to notebook conda which is an extension to jupyter
kernel to set the kernel for a notebook’s execution. Once the installation is done, write the
following command to open the Jupyter Notebook.
jupyter notebook
The Jupyter Notebook opens in the default browser with http://localhost:8888/tree URL.
57
In this page, click on New and select Python3 which would open a new Jupyter notebook
with Python3 as the default language.
As we have learnt, Jupyter Notebook is a Graphical User Interface (GUI) which means
that the Notebook interface contains a lot of easily-accessible tools for making the work
easier as all of them are clicks away.
Let us take a tour around the Notebook and understand its features.
1. Menu Bar
58
Jupyter Notebook has its own Menu bar which has the following options:
1. File: In the file menu, you can create a new Notebook or open a pre-existing one.
This is also where you would go to rename a Notebook. I think the most interesting
menu item is the Save and Checkpoint option. This allows you to create checkpoints
that you can roll back to if you need to.
2. Edit Menu: Here you can cut, copy, and paste cells. This is also where you would go
if you wanted to delete, split, or merge a cell. You can reorder cells here too.
59
3. View menu: The View menu is useful for toggling the visibility of the header and
toolbar. You can also toggle Line Numbers within cells on or off. This is also where
you would go if you want to mess about with the cell’s toolbar.
60
4. Insert menu: The Insert menu is just for inserting cells above or below the currently
selected cell.
5. Cell menu: The Cell menu allows you to run one cell, a group of cells, or all the cells.
You can also go here to change a cell’s type, although the toolbar is more intuitive for
that. The other handy feature in this menu is the ability to clear a cell’s output.
61
6. Kernel Menu: The Kernel cell is for working with the kernel that is running in the
background. Here you can restart the kernel, reconnect to it, shut it down, or even
change which kernel your Notebook is using.
7. Widgets Menu: The Widgets menu is for saving and clearing widget state. Widgets
are basically JavaScript widgets that you can add to your cells to make dynamic
content using Python (or another Kernel).
8. Help Menu: Finally, you have the Help menu, which is where you go to learn about
the Notebook’s keyboard shortcuts, a user interface tour, and lots of reference
material.
62
Other than the Menu Bar, a tool bar is also given for our ease in the Notebook interface. Let
us get to know about each of the tools.
63
Stop Break execution of the selected cell.
Restart & Restart the kernel and re-run the whole notebook.
Run all
64
Chapter 4 - More About Lists and Tuples
Introduction to Lists
As studied in the previous section, List is a sequence of values of any type. Values in the list
are called elements / items. List is enclosed in square brackets.
Example:
a = [1,2.3,"Hello"]
List is one of the most frequently used and very versatile data type used in Python. A
number of operations can be performed on the lists, which we will study as we go forward.
Example:
#empty list
empty_list = []
#list of integers
age = [15,12,18]
Note: A list can also have another list as an item. This is called nested lists.
# nested list
student marks = ["Aditya", "10-A", [ "english",75]]
65
List Index
A list index is the position at which any element is present in the list. Index in the list starts
from 0, so if a list has 5 elements the index will start from 0 and go on till 4. In order to
access an element in a list we need to use index operator [].
Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
In order to access elements using negative indexing, we can use the negative index as
mentioned in the above figure.
language = p
['p','y','t','h','o','n'] e
Accessing print(my_list[0])
Using List print(my_list[4])
Index language = Y
['p','y','t','h','o','n'] Error! Only Integer
print(my_list[4.0]) can be used for
indexing
Accessing n_list = [“Happy”,[2,0,1,5]] A
Value in a print(n_list[0][1]) 5
nested list print(n_list[1][3])
66
Adding Element to a List
We can add an element to any list using two methods :
1) Using append() method
2) Using insert() method
3) Using extend() method
67
extend() List = [1,2,3,4] [1, 2, 3, 4]
method print("Initial List: ")
print(List) List after Extend
Operation:
# Addition of multiple [1, 2, 3, 4, 8,
elements 'Artificial',
# to the List at the end 'Intelligence']
# (using Extend Method)
List.extend([8, 'Artificial',
'Intelligence'])
print("\nList after Extend
Operation: ")
print(List)
Elements can be added to the List by using built-in append() function. Only one element at a
time can be added to the list by using append() method, for addition of multiple elements
with the append() method, loops are used. Tuples can also be added to the List with the use
of append method because tuples are immutable. Unlike Sets, Lists can also be added to
the existing list with the use of append() method.
68
Using remove() method
Note – Remove method in List will only remove the first occurrence of the searched element.
69
Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to
print a specific range of elements from the list, we use Slice operation. Slice operation is
performed on Lists with the use of colon(:). To print elements from beginning to a range use
[:Index], to print elements from end use [:-Index], to print elements from specific Index till the
end use [Index:], to print elements within a range, use [Start Index: End Index] and to print
whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.
70
using slice operation: ") slice operation:
print(Sliced_List)
['G','O','O','D','M',
'O',
'R','N','I','N','G']
Slicing # Creating a List Initial List:
using List= ['G','O','O','D','M','O', ['G','O','O','D','M',
negative 'R','N','I','N','G']
'O',
index of list print("Initial List: ")
'R','N','I','N','G']
print(List)
71
List Methods
Some of the other functions which can be used with lists are mentioned below:
Now that you have learnt the basic concepts of Lists in python, it is time for us to get our
hands on to practicing about list using a Jupyter Notebook.
To open jupyter notebook, go to start menu and open anaconda prompt and jupyter
notebook in it.
Let’s Practice
Go through the List Jupyter Notebook to get an experiential learning experience for Lists. To
download the Jupyter Notebook, go to the following link : http://bit.ly/lists_jupyter
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
Introduction to Tuples
Tuple is a collection of Python objects which is ordered and unchangeable. The sequence of
values stored in a tuple can be of any type, and they are indexed by integers. Values of a
tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more
72
common to define a tuple by closing the sequence of values in parentheses. This helps in
understanding the Python tuples more easily.
Example
Example
#Creating an empty Tuple
Tuple1 = ()
Accessing of Tuples
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an element
outside of tuple (for example, 6, 7,...) will raise an IndexError. The index must be an integer;
so, we cannot use float or other types. This will result in TypeError.
Example
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets
deleted by the use of del() method.
Example
num = (0, 1, 2, 3, 4)
del num
73
Test Your Knowledge
Q1) What is the difference between a list and a tuple ?
Q2) Explain the different ways of slicing a list with a help of an example.
Q3) What is negative indexing ? Explain with an example.
Q4) Mention the methods to remove elements from a list.
Q5) What is the method to delete an element from a tuple?
74
Chapter 5 - Flow of Control and Conditions
In the programs we have seen till now, there has always been a series of statements
faithfully executed by Python in exact top-down order. What if you wanted to change the flow
of how it works? For example, you want the program to take some decisions and do different
things depending on different situations, such as printing 'Good Morning' or 'Good Evening'
depending on the time of the day?
As you might have guessed, this is achieved using control flow statements. There are three
control flow statements in Python - if, for and while.
Flow of
Control and
Conditions
While
If Statement For Statement
Statement
If Statement
On the occasion of World Health Day, one of the schools in the city decided to take
an initiative to help students maintain their health and be fit. Let’s observe an
interesting conversation happening between the students when they come to know
about the initiative.
75
There come situations in real life when we need to make some decisions and based on
these decisions, we need to decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these decisions
we will execute the next block of code.
● if statement
● if..else statements
● if-elif ladder
76
If Statement
The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block).
Syntax:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
Note:
1) In Python, the body of the if statement is indicated by the indentation. Body starts with
an indentation and the first unindented line marks the end.
2) Python interprets non-zero values as True. None and 0 are interpreted as False.
77
Example :
num = 3
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
num = -1
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is
executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
78
Python if..else Flowchart
Example of if...else
In the above example, when if the age entered by the person is greater than or equal to 18,
he/she can vote. Otherwise, the person is not eligible to vote
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
79
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
Marks = 60
80
Python Nested if statements
We can have an if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. This can get confusing, so must be avoided if it can be.
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Let’s Practice
Let’s Go through the If-Else Jupyter Notebook to get an experiential learning experience for
If-Else. To download the Jupyter Notebook, go to the following link : http://bit.ly/ifelse_jupyter
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
81
The For Loop
The for..in statement is another looping statement which iterates over a sequence of objects
i.e. go through each item in a sequence. We will see more about sequences in detail in later
chapters. What you need to know right now is that a sequence is just an ordered collection
of items.
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
82
# variable to store the sum
sum = 0
The sum is 48
The while statement allows you to repeatedly execute a block of statements as long as a
condition is true. A while statement is an example of what is called a looping statement.
A while statement can have an optional else clause.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False. In Python, the
body of the while loop is determined through indentation. Body starts with indentation and
the first unindented line marks the end. Python interprets any non-zero value
as True. None and 0 are interpreted as False.
83
Flowchart of while Loop
n = 10
while i <= n:
sum = sum + i
i = i+1 # update counter
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).
84
We need to increase the value of the counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).
Let’s Practice
Let’s Go through the flow control Jupyter Notebook to get an experiential learning
experience for ‘for’ and ‘while’ loop . To download the Jupyter Notebook, go to the following
link : http://bit.ly/loops_jupyter
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
85
Chapter 6 : Introduction to Packages
Recap
Till now, you have worked around various python syntaxes. Conditional statements, Control
flow statements, variables, datatypes, etc. are some of the concepts you now are quite
familiar with. Let us test your skills and see how well have you understood it all.
CHALLENGE TIME!
Here are 5 questions. Go through them individually and try answers them all.
86
Was the quiz easy?
Or did you find a need to take a look back at the concepts?
Analyze your score and mention it here:
_________________________________________________________________________
Introduction
Let us assume we need to prepare the final result of your class. In your class, let’s say there
are 40 students. What should be the steps to prepare the result?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
Let’s see.
Step 1: Collect the exam scores for Mathematics, Science, Social Science, Hindi and
English for all the students.
Step 2: Make a database (list) of students and their marks in each subject. It might look like
this:
87
Student’s Marks in Marks in Marks in Marks Marks in
Roll No. Science Mathematics Social Science in Hindi English
Student 1 89 75 73 84 78
Student 2 54 65 57 75 48
… … … … … …
Student 98 100 97 94 97
40
Step 3: New columns get added to the database for total marks and the percentage.
Step 4: Finally, the database has been successfully created. Now, we need to analyze class
performance as a whole. In this case, statistics come to our rescue. Various parameters that
come into picture are mentioned below. Can you write how to find them all? List them down!
88
5. Top 10 students of the class.
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
After going through this process, we can say that preparing the exam result manually is a
tedious and time-consuming process. Therefore, it should be automated by creating a
python script!
As you have already learnt a lot of Python concepts, list down the ones which can be used to
create a python script of result creation.
There are a lot of functions which can be used in this process. But as it is all about numbers,
we need to look for something that explicitly works around numbers so that the work
becomes easier. With python, we get the advantage of using open-sourced packages
available on the internet. But what are packages? Let’s find out.
89
What is a package?
Here, we can draw analogy for packages with the book shelf. The history bookshelf is
nothing but a package which contains multiple books of similar type and provides the user
with a variety to choose from to make it easier for them to find out the exact information
needed.
In other words, a package is nothing but a space where you can find codes or functions or
modules of similar type. There are various packages readily available to use for free (perks
of python being an open-sourced language) for various purposes.
Some of the readily available packages are:
90
Package Installation
Using these packages is easy. All we need to do is install the package and import it
wherever required.
Any package can be installed by directly writing the following command in the Anaconda
Prompt:
conda install numpy
The name of package can be replaced at the end of the statement.
Once you begin the installation, after a bit of processing, the prompt would ask if you wish to
proceed for the installation or not:
Press Y to continue with the installation. Within a few minutes, the packages will be installed
and would be ready to use.
Meaning: Import numpy in the file to use its functionalities in the file to which it has been
imported.
Meaning: import only one functionality (array) from the whole numpy package. While this
gives faster processing, it limits the package’s usability.
Meaning: Import only one functionality (array) from the whole numpy package and refer to it
as arr wherever it is used.
A lot of other combinations can also be explored while importing packages like importing
multiple functionalities of a package in a single statement, etc.
91
What is NumPy?
NumPy, which stands for Numerical Python, is the fundamental package for mathematical
and logical operations on arrays in Python. It is a commonly used package when it comes to
working around numbers. NumPy gives a wide range of arithmetic operations around
numbers giving us an easier approach in working with them. NumPy also works with arrays,
which is nothing but homogenous collection of Data.
An array is nothing but a set of multiple values which are of same datatype. They can be
numbers, characters, Booleans, etc. but only one datatype can be accessed through an
array. In NumPy, the arrays used are known as ND-arrays (N-Dimensional Arrays) as
NumPy comes with a feature of creating n-dimensional arrays in python.
An array can easily be compared to a list. Let us take a look how different they are:
Since NumPy package is not included in the basic Python installation, we need to install it
separately. Once it is installed, it can be readily used in any Python code whenever
imported.
92
Exploring NumPy!
NumPy package provides us with various features and functions which helps us in arithmetic
and logical operations. Let us look at some of them:
Function Code
Creating a Numpy Array numpy.array([1,2,3,4,5])
Creating a 2-Dimensional zero array (4X3 – numpy.zeros((4,3))
4 rows and 3 columns)
Creating an array with 5 random values numpy.random.random(5)
Creating a 2-Dimensional constant value numpy.full((3,4),6)
array (3X4 – 3 rows and 4 columns) having
all 6s
Creating a sequential array from 0 to 30 with numpy.arrange(0,30,5)
gaps of 5
One of the features of array is that we can perform arithmetic functions on the elements of
the array directly by performing them on the whole array.
Let us assume the array is “ARR” and it has been initialized as:
ARR = numpy.array([1,2,3,4,5])
Now, let us look at various operations that could be implemented on this array:
Function Code
Adding 5 to each element ARR + 5
Divide each element by 5 ARR / 5
Squaring each element ARR ** 2
Accessing 2nd element of the array (element
ARR[1]
count starts from 0)
Multiplying 2 arrays
ARR * BRR
{consider BRR = numpy.array([6,7,8,9,0]) }
As you can see, direct arithmetical operations can be implemented on individual array
elements just by manipulating the whole array variable.
93
Let us look at the functions which talk about the properties of an array:
Function Code
Type of an array type(ARR)
Check the dimensions of an array ARR.ndim
Shape of an array ARR.shape
Size of an array ARR.size
Datatype of elements stored in the array ARR.dtype
Function Code
Finding out maximum element of an array ARR.max()
Finding out row-wise maximum elements ARR.max(axis = 1)
Finding out column-wise minimum elements ARR.min(axis = 0)
Sum of all array elements ARR.sum()
Let’s Practice!
TASK 1
To understand these functions better, let us try and execute all the functions we read above
on a Jupyter Notebook. To download the Jupyter Notebook, go to the following link:
http://bit.ly/numpy_jupyter and download NumPy Basic notebook.
TASK 2
Go through the NumPy Jupyter Notebook to get an experiential learning experience for
NumPy. To download the Jupyter Notebook, go to the following link :
http://bit.ly/numpy_jupyter and download NumPy Advance notebook
Note:
To open Jupyter notebook, go to start menu → open anaconda prompt → write “jupyter
notebook”
94
Additional Resources
• NCERT Class 11 Python Text Book
• Introduction to Python :
o https://www.w3schools.com/python/python_intro.asp
o https://www.programiz.com/python-programming/first-program
o https://www.geeksforgeeks.org/python-programming-language/
• Introduction to Flowchart and Algorithm: https://www.edrawsoft.com/explain-
algorithm-flowchart.php
• Python Lists : https://www.w3schools.com/python/python_lists.asp
• Python While Loop : https://www.w3schools.com/python/python_while_loops.asp
• Python For Loop: https://www.w3schools.com/python/python_for_loops.asp
• Python Condition Statements: https://www.w3schools.com/python/python_conditions.asp
• Python Packages: https://www.w3schools.com/python/python_modules.asp
95