Introduction to Python
Jupyter Notebook
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 and it is an interactive way
of running python code in the terminal using the REPL model. (Read Eval Print Loop)
Jupyter Notebook is an open-source, web-based interactive environment, which allows you to create
and share documents that contain live code, mathematical equations, graphics, maps, plots,
visualizations, and narrative text. It integrates with many programming languages like Python, PHP, R,
C#, etc.
Advantages of Jupyter Notebook
1. All in one place: As you know, Jupyter Notebook is an open-source web-based interactive
environment that combines code, text, images, videos, mathematical equations, plots, maps,
graphical user interface and widgets to a single document.
2. Easy to convert: Jupyter Notebook allows users to convert the notebooks into other formats
such as HTML and PDF. It also uses online tools and nbviewer which allows you to render a
publicly available notebook in the browser directly.
3. Easy to share: Jypyter Notebooks are saved in the structured text fies(JSON format), which
makes them easily shareable.
4. Language independent: Jupyter Notebook is platform-independent because it is represented
as JSON (JavaScript Object Notation) format, which is a language independent, text-based file
format. Another reason is that the notebook can be processed by any programing language,
and can be converted to any file formats such as Markdown, HTML, PDF, and others
5. Interactive code: Jupyter notebook uses ipywidgets packages, which provide many common
user interfaces for exploring code and data interactivity
Installing Jupyter Note Book
1. Installation using Anaconda
171
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. Jupyter notebook can easily be accessed using the
Anaconda Prompt with the help of a local host.
2. Installation using pip:
Jupyter note book can be installed also using the following code in command prompt
>python-m pip install jupyter
Kernels in Jupyter Notebook
A kernel provides programming language support in Jupyter. IPython is the default kernel for Jupyter
Notebook. Therefore, whenever we need to work with Jupyter Notebook in a virtual environment, we
first need to install a kernel inside the environment in which the Jupyter notebook will run.
Virtual environment
A virtual environment is a tool that helps to keep dependencies required by different projects
separated, by creating isolated Python virtual environments for them. This is one of the most important
tools that most of the Python developers use.
Imagine a scenario where we are working on two Python-based projects and one of them works on
Python 2.7 and the other uses Python 3.7. In such situations virtual environment can be really useful to
maintain dependencies of both the projects as the virtual environments will make sure that these
dependencies are not conflicting with each other and no impact reaches the base environment at any
point in time. Thus, different projects developed in the system might have another environment to keep
their dependencies isolated from each other.
172
Creating virtual environments is an easy task with Anaconda distribution. Steps to create one are:
1. Open Anaconda prompt.
2. As we open the Anaconda prompt, we can see that in the beginning of the prompt message, the
term (base) is written. This is the default environment in which the anaconda works. Now, we can
create our own virtual environment and use it so that the base does not get affected by anything
that is done in the virtual environment.
3. Let us now create a virtual environment named env. To create the environment, write conda create
-n env python=3.7
4. After some processing, the prompt will ask if we wish to proceed with installation or not. Type y on
it and press enter. Once we press enter, the packages will start getting installed in the environment.
173
5. Depending upon the internet speed, the downloading of packages might take varied time.
6. Once all the packages are downloaded and installed, we will get a message.
7. This shows that our environment called env has been successfully created. Once an environment
has been successfully created, we can access it by writing the following:
Conda active env
This would activate the virtual environment and we can see the term written in brackets has
changed from (base) to (env).Now our virtual environment is ready to be used. But, to open and
work with jupyter notebooks in this environment, we need to install the packages which help in
working with jupyter notebook. These packages get installed by default in the base environment
when anaconda gets installed. To install Jupyter Notebook dependencies, we need to activate our
virtual environment env and write Conda insatll ipykernal nb_cond jupyter It will again ask if we
wish to proceed with the installation, type Y to begin the installation. Once the installations are
complete, we can start working jupyter notebooks in this environment.
Introduction to Python
Python is a programming language which was created by Guido Van Rossum . It can be used to follow
both procedural approach and object-oriented approach of programming. Python has a lot of
functionalities which makes it so popular to use.
Why Python for AI?
Artificial intelligence is the trending technology of the future. We can see so many applications around
us. If we as individuals would also like to develop an AI application, we will need 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:
1. Easy to learn, read and maintain: Python has few keywords, simple structure and a clearly
defined syntax. A program written in Python is fairly easy to maintain.
2. A Broad Standard Library: Python has a huge bunch of libraries with plenty of built in functions
to solve variety of problems.
3. Interactive mode: Python has support for an interactive mode which allow interactive testing and
debugging of snippets of code.
174
4. Portability and compatibility: Python can run on a wide variety of operating systems and
hardware platforms, has the same interface on all platforms.
5. Extendable: We can add low level modules to the python interpreter. These modules enable
programmers to customize their tools to be more efficient.
6. Database and scalable : Python provides interfaces to all major open source and commercial
databases along with a better structure and support for large programs than shell scripting.
Applications of Python There exist a wide variety of applications when it comes to Python. Some of the
applications are:
PYTHON BASICS
Comments
Comments are the statements which are incorporated in the code to give a better understanding of code
statements to the user. There are two types of comments in python.
1. Single Line 2. Multi Line
Single Line comment
A single-line comment is used to add some explanatory text in the program for better
understanding of the next line. A # sign is used to write a single line comment in the python program For
example, # statement to add two numbers res = 6 + 7 #Print the result print(res)
Multiline comments
The multiline comments are written in python using triple quotes. You can write number lines
starting with triple quotes and end with triple quotes. For example, '''Write a python program to display
the difference between two numbers, the first number should be larger than second number''' n1=5 n2=2
175
res=n1 - n2 print(res) Keywords (Reserved Words) Keywords are the reserved words or pre-defined words
with a special meaning to the machine by default. So the user cannot use them anywhere else or it cannot
be changed or modified in the entire program. They are always case-sensitive.
Keywords in Python
Identifiers
Identifiers are names used in programs to identify small units of programs such as variables,
objects, classes, functions etc. Identifiers defined by the following few rules as follows: 1. It can be a
combination of numbers and letters 2. It must start alphabets or underscore 3. Special characters are not
allowed in identifiers name except underscore 4. Spaces are not allowed in identifier names, underscore
can be used to separate two words 5. Upper Case and Lower Case letters are treated differently.
Valid Identifiers: total_student, mydata, num1, result etc
Invalid Identifiers: break, 1num, total student etc
Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables as a
container that holds data which can be changed later throughout programming.
For example, a=10 b=20
176
These declarations make sure that the program reserves memory for two variables with the names a and
b. The variable names stand for the memory location.
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.
Datatypes
In program, you have a choice to use any type of data such as real numbers, numbers with decimals,
numbers without decimals, text, etc. These type of data is defined by datatype in Python. The python
interprets the type of the variable according to the value stored in the variable. Follow the below-given
link to know more about data types.
Datatypes in Python
Numbers None Sequence Sets Mapping Boolean
Integer String Dictionary
Floating Point tuple
Complex List
Python Input and Output
We use the print() function to output data to the standard output device (screen). We can also output
data to a file. An example is given below. a = "Hello World!" print(a)
The output of the above code will be: Hello World!
Example Code Output
a = 30 50
b = 20
print(a + b)
print(5 + 10) 15
print("My name is Sudhanshu") My name is Sudhanshu
name= ‘Sudhanshu ‘ My name is Sudhanshu
print("My name is “,name)
n=5 I have 5 Apples !
print("I have",n,"Apples !")
177
input() function
The input() function is used to accept values from the user at runtime. This function accepts and returns
the text data by default. Therefore, you need to specify the data type if you want to use numbers or any
other datatype. This process is known as typecasting Str = input() # Python expects the input to be of
string datatype
Number = int(input()) # Input string gets converted to an integer value before assignment
Value = float(input()) # Input string gets converted to a decimal value before assignment.
Python Operators
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 operators. Values and variables when used with operators are known as operands.
1. Arithmetic Operators
Operator Meaning Expression Result
+ Addition 10+20 30
- Subtraction 20-10 10
* Multiply 10*20 200
/ Divide 20/10 2
// Integer division/floor 15//2 7
division
** Power 3**3 27
% Remainder 15%2 1
2. Conditional Operators
Operator Meaning Expression Result
> Greater Than 10>15 false
< Less Than 10<15 true
>= Greater than equal to 10>=10 true
<= Less than equal to 15<=10 false
== Equal to 10==15 false
!= Not equal to 10!=15 true
3. Logical operators
Operator Meaning Expression Result
and and operator true and false false
or or operator true or false true
not not operator not true false
178
4. Assignment Operators
Operator Meaning Equivalent
= X=5 X=5
+= X+=5 X=X+5
-= X-=5 X=X-5
*= X*=5 X=X*5
/= X/=5 X=X/5
Conditional Statements
While coding in Python, sometimes we need to take decisions. For example, if a person needs to create a
calculator with the help of a Python code, he/she needs to take in 2 numbers from the user and then ask
the user about which function he/she wishes to operate. Now, according to the user’s choice, the selection
of function would change. In this case, we need the machine to understand what should happen when.
This is where conditional statements help. Conditional statements help the machine in taking a decision
according to the condition which gets fulfilled. There exist different types of conditional statements in
Python.
There are three types of conditional statements.
1. if statements
2. if-else statements
3. if elif statement
Simple if:
The statement inside the if block are executed only when condition is true, otherwise not.
Syntax
if <condition>:
Statement(s)
Example:
if a < b :
print(‘a is greater’)
179
if-else statement
The statements inside the if block are executed only when condition is true, otherwise the statements in
the else block are executed.
Syntax
if <condition>:
Statement(s)
else:
statements
Example:
if a < b :
print(‘a is greater’)
else:
print(‘b is greater’)
if elif statement
The if...elif...else statement allows you to check for multiple test expressions and
execute different codes for more than two conditions.
Syntax
if <condition>:
Statement(s)
elif <condition>:
Statement(s)
Example
print('****program to find greatest of 3 numbers****')
num1=int(input('enter first number: '))
num2=int(input('enter second number: '))
num3=int(input('enter third number: '))
if num1 > num2 and num1 > num3:
print('The greatest of the three nos. is : ',num1)
elif num2 > num3 and num2 > num1:
180
print('The greatest of the three nos. is : ',num2)
elif num3 > num1 and num3 > num2:
print('The greatest of the three nos. is :',num3)
else:
print('any two nos are equal')
Nested if-else Statements
#Check leap year / divisibility
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else: print("{0} is not a leap year".format(year))
Iteration statements (loop)
These are used to execute a block of statements as long as the condition is true. Loops statements are
used when we need to run same code again and again.
Python Iteration (Loops) statements are of two type :-
1. for Loop
2. while Loop
For Loop
181
It is used to iterate over items of any sequence, such as a list or a string. Syntax for val in sequence: #here
val will take value of each element in the sequence statements
Example:
for I in [1,2,3,4,5]:
print(I*5)
OUTPUT:
10
15
20
25
range() Function
This function generates a sequence of numbers based on the parameters passed.
Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence. Python use range()
function in three ways:
a. range(stop)
b. range(start,stop)
c. range(start,stop,step)
Note:
All parameters must be integers.
All parameters can be positive or negative.
a. range(stop): By default, It starts from 0 and increments by 1 and ends upto stop, but not including stop
value.
b. range(start,stop) : It starts from the start value and upto stop, but not including stop value.
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by adding or
subtracting the value.
Example: (i) (ii)
182
for x in range(4):
print(x)
Output:
# program of python to print first n natural number and its sum.
num=int(input(‘Enter number’))
sum=0
for i in range(1,n+1):
print(i)
sum=sum+i
print(‘Sum of numbers’, sum)
While Loop
It is used to execute a block of statement if a given condition is true and when the condition become false,
the control will come out of the loop. The condition is checked every time at the beginning of the loop.
Syntax
while (condition):
[statements]
Update expression
183
example
Python Packages
A package is nothing but a space where we 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.
To use any package in Python, we need to install it. Installing Python packages is easy. Steps for package
installation are:
1. Open Anaconda Navigator and activate your working environment.
2. Let us assume we wish to install the numpy package. To install this package, simply write:
conda install numpy
3. It will ask us to type Y if we wish to proceed with the installations. As soon as we type Y, the installations
will start and our package will be installed in our selected environment.
4. We can also install multiple packages all at once by mentioning all of them in one line. For example, if
we wish to install numpy, pandas and matplotlib package in our working environment. For this, simply
write:
184
conda install numpy pandas matplotlib
This code will install these three packages altogether in our environment. Now, once the packages are
installed, we can start using them by importing them in the file where they are required. As soon as we
open our Jupyter Notebook, include the package in the notebook bywriting the import command.
Importing a package can be done in various ways:
import numpy
Meaning: Import numpy in the file to use its functionalities in the file to which it has been imported.
from numpy import array
Meaning: import only one functionality (array) from the whole numpy package. While this gives faster
processing, it limits the package’s usability.
from numpy import array as arr
Meaning: Import only one functionality (array) from the whole numpy package and refer to it as arr
wherever it is used.
Some of the readily available packages are:
NumPy
OpenCV
Matplotlib
NLTK
Pandas
185
CLASS 10 ARTIFICIAL INTELLIGENCE (417) SUGGESTED PRACTICAL LIST 2024-25
Activity 1: To print personal information like Name, Father’s Name, Class, School Name.
Code:
print("My Name is:","Rajesh Kumar")
print("My Father Name is:","Rakesh Kumar")
print("My class is 10-A")
print("My School is","PM SHRI KENDRIYA VIDYALAYA")
o/p:
My Name is: Rajesh Kumar
My Father Name is: Rakesh Kumar
My class is 10-A
My School is PM SHRI KENDRIYA VIDYALAYA
Activity 2: Write a Python code to calculate Simple Interest if the principle_amount =
2000 rate_of_interest = 8 time = 10
Code:
P=2000
T=10
R=8
SI=(P*T*R)/100 # calculates simple interest
print "Simple Interest is",SI)
o/p:
Simple Interest is 1600.0
Activity 3: Write a Python code to calculate Area of a triangle with Base and Height
Code:
B=int(input("Enter Base of a rectangle")) # reading base value of the rectangle
H=int(input("Enter Height of a rectangle")) # reading height of the rectangle
print("Area of a rectangle is",0.5*B*H) # displays are of the rectangle
186
o/p:
Enter Base of a rectangle5
Enter Height of a rectangle4
Area of a rectangle is 10.0
Activity 4: Write a Python code to check whether a person is eligible to vote or not.
Code:
Age=int(input("Enter person’s age"))
if Age>=18: # checking the condition
print("Person is Eligible to vote")
else:
print("Person is not Eligible to vote")
o/p:
Enter person’s age 21
Person is Eligible to vote
Activity 5: Write a Python code to print sum of first 10 natural numbers.
Code:
S=0
for i in range(1,11):
S=S+i
print("Sum of first 10 natural numbers is",S)
o/p:
Sum of first 10 natural numbers is 55
Activity 6: Write a Python code to assign the Grade based on the given percentage:
Code:
per=float(input("Enter students percentage"))
if per>=90: #checking the condition
grade="A" # assigning grade
elif per>=70 :
187
grade="B"
elif per>=50:
grade="C"
elif per>=33:
grade="D"
else:
grade="E"
print("Perntage is",per)
print("Grade is",grade)
o/p: Enter students percentage89
Perntage is 89.0
Grade is B
Activity 7: Write a program to create a list and display list elements.
Code:
l=[]
n=int(input("Enter length of the list"))
for i in range(n):
a=eval(input("Enter list element"))
[Link](a)
print("Created list is",l)
o/p:
Enter length of the list5
Enter list element10
Enter list element20.5
Enter list element45
Enter list element78
Enter list element23
188
Created list is [10, 20.5, 45, 78, 23]
Activity 8: Write a program to add the elements of the two lists.
Code:
l1=[20,30,40]
l2=[30,50,10]
l3=l1+l2
print("Addition of",l1,"and",l2,"is",l3)
o/p:
Addition of [20, 30, 40] and [30, 50, 10] is [20, 30, 40, 30, 50, 10]
Activity 9: Write a program to calculate mean, median and mode using Numpy
Code:
import numpy as np
import statistics as st
l=[30,20,50,60,20]
l1=[Link](l)
print("Mean of",l1,"is",[Link](l1))
print("Median of",l1,"is",[Link](l1))
print("Mode of",l1,"is",[Link](l1))
o/p:
Mean of [30 20 50 60 20] is 36
Median of [30 20 50 60 20] is 30
Mode of [30 20 50 60 20] is 20
Activity 10: Write a program to display line chart from (2,5) to (9,10).
Code:
import [Link] as plt
189
x=(2,9)
y=(5,10)
[Link](x,y)
[Link]("Line chart")
[Link]()
o/p:
Activity 11: Write a program to display a scatter chart for the following points (2,5),
(9,10),(8,3),(5,7),(6,18).
Code:
import [Link] as plt
x=[2,9,8,5,6]
y=[5,10,3,7,18]
[Link](x,y)
[Link]("Line chart")
[Link]()
o/p:
Activity 12: Write a program to display bar chart for the following data with appropriate
titles:
Subjects=[“Eng”,”Sci”,”Soc”,”Maths”,”AI”]
Marks=[89,87,78,90,99]
Code:
190
import [Link] as plt
Sub=["Eng","Sci","Soc","Maths","AI"]
Marks=[89,87,78,90,99]
[Link](Sub,Marks)
[Link]("Term-1 Performance")
[Link]("Subjects")
[Link]("Marks")
[Link]()
0/p:
Activity 13: Write a program to display histogram for the following data with appropriate
titles:
stu=[5,14,17,23,34,50,20,34,24,56,45,34,23,34,32,9,8,22,24,34,55,66,23,23 ]
Code:
import [Link] as plt
stu=[5,14,17,23,34,50,20,34,24,56,45,34,23,34,32,9,8,22,24,34,55,66,23,23]
191
[Link](stu,bins=[0,10,20,30,40,50,60,70])
[Link]("Marks")
[Link]("[Link] Students")
[Link]("Marks Obtained by the Students")
[Link]()
o/p:
Activity 14: Write a program to display Pie-chart for the following data with appropriate
titles:
Code:
import [Link] as plt
x=["Food","Rent","Shopping","Educcation","others"]
values=[20,30,25,35,50]
[Link](values,labels=x)
[Link]("Expenditure")
192
[Link]()
Activity 15: Read CSV file saved in your system and display 5 rows
Code:
import pandas as pd
df=pd.read_csv(r"C:\Users\ADMIN\Desktop\[Link]",nrows=10)
print(df)
o/p:
RNO NAME MARKS
0 1 HARI 67
1 2 RAMESH 89
193
2 3 SOMESH 56
3 4 RAJESH 78
4 5 BHIMESH 45
Activity 16: Read CSV file saved in your system and display its information
Code:
import pandas as pd
df=pd.read_csv(r"C:\Users\ADMIN\Desktop\[Link]",nrows=10)
print(df)
o/p:
RNO NAME MARKS
0 1 HARI 67
1 2 RAMESH 89
2 3 SOMESH 56
3 4 RAJESH 78
4 5 BHIMESH 45
5 6 SRIKANTH 67
6 7 SRINIVAS 89
7 8 SANDHYA 90
8 9 SADANA 56
9 10 RAJU 45
Activity 17: Write a program to read an image and display using Python
Code:
import cv2
img=[Link]("[Link]")
[Link]('Image',img)
[Link](0)
o/p:
194
Activity 18: Write a program to read an image and display image shape and size
using Python
Code:
import cv2
img=[Link](r"C:\Users\ADMIN\Desktop\[Link]")
[Link]('myimg',img)
print("The shape of the image is",[Link])
print("The Size of the image is",[Link])
[Link](0)
195
o/p:
The shape of the image is (148, 259, 3)
The Size of the image is 114996
196