0% found this document useful (0 votes)
29 views

Module 2 - Python

This document discusses Python programming and its role in artificial intelligence. It provides an overview of Python's advantages for AI development, including its popularity, open source nature, simple syntax, and extensive libraries for scientific computing and machine learning. The document then covers basic Python data types, operations on strings and lists, and operations on dictionaries. It demonstrates how to add, update, remove and iterate through elements in lists and dictionaries.

Uploaded by

Anurag Sathian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Module 2 - Python

This document discusses Python programming and its role in artificial intelligence. It provides an overview of Python's advantages for AI development, including its popularity, open source nature, simple syntax, and extensive libraries for scientific computing and machine learning. The document then covers basic Python data types, operations on strings and lists, and operations on dictionaries. It demonstrates how to add, update, remove and iterate through elements in lists and dictionaries.

Uploaded by

Anurag Sathian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

MODULE 2

Demonstrate python program to solve the problems in AI

ROLE OF PYTHON IN AI

Python has become a key player in AI development due to its many advantages over other
Programming languages. Let’s explore some of the key benefits of using Python for AI.

PYTHON
• Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:
• web development (server-side)
• software development
• mathematics
• system scripting
• Artificial intelligence

FEATURES OF PYTHON

• Python is also regarded as a general-purpose ,open source programming


language, so used in a variety of technologies and fields.

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,


etc).

• Python has a simple syntax similar to the English language.

• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.

ROLE OF PYTHON IN AI
• Python is the most basic programming language ,it is the simplest oop
oriented language.
• Python is one of the best languages for AI since it has prebuilt libraries
like Numpy for doing scientific calculations, Scipy for high-end
computation, and Pybrain for machine learning.

• Python programmers from across the world provide substantial support


(Large community)and guidance through tutorials and forums.

• With very few alterations to the fundamentals of coding, Python is


among the most flexible and well-known solutions for a variety of
platforms and technologies. Python is platform-independent.

• Python is an Interpreted language

Basic datatypes in PYTHON


I. Text Type: Str

II. Numeric Types: int, float, complex

III. Sequence Types: list, tuple, set, range


IV. Mapping Type: dict
V. Boolean Type: bool
VI. None Type: NoneType

Setting the Data Type

• The datatype is set , when value is assigned to a variable.


x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana",
list
"cherry"]
x = ("apple", "banana",
tuple
"cherry")
Getting the Data Type

• Datatype can be displayed using the function type()


Eg:
X=5
Print((type(x))

Output
<class ‘int’>

I.String DT

• Strings in python are surrounded by either single quotation marks, or double quotation marks.
• 'hello' is the same as "hello".
Eg:
a = "Hello"
print(a)
II. Numeric DT

There are 3 numeric datatypes in python.

• Int
• Float
• Complex
example

x = 1 # int
y = 2.8 # float
z =2+1j # complex
III. BOOLEAN
• Boolean represent 2 values true or false
Eg:
A=10
B=20
C=A>B
print(C)

OUTPUT
FALSE
IV. Sequence type

1.LIST

• Lists are used to store multiple items in a single variable.


• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0],second item has index [1], and so on.
• Lists are created using square brackets.

Eg:
list1 = ["apple", "banana", "cherry"]
print(list1)
type(list1)

2. TUPLE
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
Eg:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

3.SET
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable(but can remove items and add new items) ,
unindexed and do not allow duplicate values.
• Sets are written with curly brackets.
Eg:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

4.RANGE
• The range() function returns a sequence of numbers starting from 0 by default ,increments by 1(by
default),and stops before a specified number.

Syntax
range(start, stop, step)
Eg:
A=set(range(2,10,2))
Print(A)

Output
{2,4,6,8}

V. Mapping type

DICTIONARY

• Dictionaries are used to store data values in key:value pairs.


• A dictionary is a collection which is ordered(older versions unordered),changeable and do not
allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values

Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict[“model”])

String Operations In Python

• Python has a set of built-in methods that you can use on strings.
• Strings in python are surrounded by either single or double quotation marks.
• strings in Python are arrays of bytes.

• Len() – used to get length of a string.


• To check if a certain phrase or character is present in a string, we can use the
keyword ’in’.

Eg:-
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
a. Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a part of the string.

Eg:
b = "Hello, World!"
print(b[2:5])
print(b[2:]
print(b[:5]

output
llo
llo World!
Hello
Negative Indexing

Use negative indexes to start the slice from the end of the string:

Eg:

b = "Hello, World!"
print(b[-5:-2])

#From: "o" in "World!" (position -5)


#To, but not included: "d" in "World!" (position -2):

output

orl

b. Concatenation
Two strings can be concatenated or join using the “+” operator in python
Eg:
string1 = "hello"
string2 = "world "
string_combined =string1+string2
print(string_combined)
C. Comparison operations

• The string comparison operator in python is used to compare two strings.


• “==” operator returns Boolean True if two strings are the same and return Boolean False if two
strings are not the same.
• “!=” operator returns Boolean True if two strings are not the same and return Boolean False if two
strings are the same.

Eg:
string1 = "hello"
string2 = "hello, world“
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string1!=string4)

d. Membership Operator “in” & “not in”

• Membership operator is used to searching whether the specific character is part/member of a given
input python string.
• “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in the
string.
• “a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a” is in
the string.

Eg:
string1 = "helloworld"
print("w" in string1)
print("hello" not in string1)
o/p:
True
false

e. Escape Sequence Operator “\”

• To insert a non-allowed character in the given input string, an escape character is used. An escape
character is a “\” or “backslash” operator followed by a non-allowed character. An example of a non-
allowed character in python string is inserting double quotes in the string surrounded by double-
quotes.
Eg:
string = "Hello world I am from \"India\"" print(string)

output
Hello world I am from "India

List Oerations in Python

I. Add Elements to a List


Lists are mutable (changeable). Meaning we can add and remove elements from a list.

Using append()
• The append() method adds an item at the end of the list. For example,

numbers = [21, 34, 54, 12]


numbers.append(32)
Print(numbers)

o/p:- [21,34,54,12,32]
Using insert()
• We use the insert() method to add an element at the specified index.

Eg:
Numbers=[10,30,40]
Numbers.insert(1,20)
Print(Numbers)

o/p:
[10,20,30,40]

II. Update contents of list

Eg:
Items=[‘car’,jeep’,’bus’]
Items[2]=‘auto’
Print(items)

o/p:
[‘car’,’jeep’,’auto’]
III. Remove an Item From a List

• Using del Statement


In Python we can use the del statement to remove one or more items from a list.

For example,

Languages=[‘swift’,’python’,’php’,’C’,’C++’]
Del languages[-1]
Print(languages)
Del languages[1:3]
Print(languages)

o/p: =[‘swift’,’python’,’php’,’C’,]
[‘swift’,’C’]

Using remove()
• We can also use the remove() method to delete a list item.
Eg:
languages=[‘swift’,’python’,’php’,’C’,’C++’]
languages.remove(‘python’)

O/P: [‘swift’,’php’,’C’,’C++’]

IV.Iterating through a List

• We can use a for loop to iterate over the elements of a list. For example,

languages=[‘swift’,’python’,’php’,’C’,’C++’]
For language in languages
print language

o/p: swift
python
php
C
C++
Dictionary Operations in Python

• In Python, a dictionary is a collection that allow to store data in key-value pairs.

Country={“unitedstates”:”Washington”,”Italy”:”rome”,”England”:”London”}
print(len(country)) # TO find length of dictionary
print(country[“united states”]) #TO access value of a dictionary item.

o/p: 3
Washington

Add Items to a Dictionary

• We can add an item to the dictionary by assigning a value to a new key (that does not exist in the
dictionary). For example,
country={“united states”:”Washington”,”England”:”London”}
country[Italy]=“Rome”
Print(country)
O/P:{“united states”:”Washington”,” England”:”London”, “Italy”:”Rome”,”}

Update items in a dictionary

• Python dictionaries are mutable (changeable). We can change the value of a dictionary element by
referring to its key. For example,

country={“united states”:”Washington”,”Italy”:”rome”,”England”:”London”}
country[Italy]=“Rome”
Print(country)

o/p:
{“united states”:”Washington”,”Italy”:”Rome”,”England”:”London”}
Remove Dictionary Items

country={“unitedstates”:”Washington”,”Italy”:”Rome”,England”:”London”}
Del country[Italy]=“Rome”
Print(country)

o/p:{“united states”:”Washington”,”England”:”London”}
Functions In Python
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
In Python a function is defined using the def keyword
Eg:
def my_function():
print("Hello from a function")

Call a function

• To call a function, use the function name followed by parenthesis

Eg:
def my_function():
print("Hello from a function")
my_function()
o/p: Hello from a function
Return values
• To let a function return a value ,use the return statement
Eg:
def my_function(x):
return 5 * x
print(my_function(3))

o/p: 15

Passing arguments to function


• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.
Eg:

def my_function(country):
print("I am from " + country)
my_function("Sweden")

o/p: I am from Sweden


Passing List As An Argument

• You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will
be treated as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List when it reaches the function.

Eg:
def my_function(fruits):
for x in fruits:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

o/p: apple
banana
cherry

Modules and Packages in Python

MODULE
• Module is same as a code library.
• Module is a file containing a set of functions .
• To create a module save the file using file extension .py
• We can use the module , by using the import statement.

Syntax: import module_name


• When using a function from a module, use the syntax:
module_name.function_name
eg:
mymodule.py
def greeting(name):
print("Hello, " + name)

Use a module
import mymodule
mymodule.greeting("John")
Variables in Module

The module can contain functions and variables of all types .


Syntax : module_name.variable_name

Eg:
mymodule.py
person1 = {"name": "John","age": 36,"country": "Norway"}

Import the module named mymodule, and access the person1 dictionary:
Eg:
import mymodule
a = mymodule.person1["age"]
print(a)

Built-in Modules in Python

• There are several built-in modules in Python, which you can import whenever you like.

Eg:
import platform
x = platform.system()
print(x)

o/p: Windows

• There is a built in function to list all the function names and variables in a module.

Eg:
import platform
x = dir(platform)
print(x)

Import from module

• We can choose only a part from module by using the keyword ‘from’.
Eg:
mymodule.py
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

from mymodule import person1


print (person1["age"])

PACKAGES IN PYTHON

• Python packages contain several modules.


• In simpler terms, Package in Python is a folder that contains various modules as files.

Creating Package
• Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2.
• Create a folder named mypckg.
• Then create two modules mod1 and mod2 in this folder.
Mod1.py
Def fun1():
print(“welcome”)
Mod2.py
Def sum(a,b)
return a+b

Import Modules from a Package


 We can import these Python modules using the from…import statement and the dot(.) operator
Syntax:
Import packagename.modulename
Eg:
From mypckg import Mod1
From mypckg import Mod2
Mod1.fun1()
A=Mod2.sum(2,3)
Print(“A”)
• We can also import the specific function also using the same syntax.

Eg:
From mypckg.Mod1 import fun1
Fun1()

PIP IN PYTHON

PIP is the package manager in python. Pip is one of the most famous and widely used package
management systems to install and manage software packages written in Python.

Pip is a recursive acronym that can stand for either "Pip *Installs* Packages" or "Pip Installs Python".
Alternatively, pip stands for "preferred installer program".

Syntax:To install Packages: pip install packagename

To uninstall packages: pip uninstall packagename


To list packages: pip list

NumPy
 NumPy is a Python library used for working with arrays.

 It also has functions for working in domain of linear algebra, fourier transform, and matrices.

 It is an open source project and you can use it freely.

 NumPy stands for Numerical Python.

 In Python we have lists that serve the purpose of arrays, but they are slow to process.

 NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.

 The array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.

 Arrays are very frequently used in data science, where speed and resources are very important.
Install NumPy

pip install numpy

create a numpy array


import numpy as np
a = np.array([1, 2, 3, 4, 5])

print(a)

o/p: [1 2 3 4 5]

check the version of numpy


import numpy as np

print(np.__version__)

o/p: 1.25.0

check the type of a numpy array


import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

o/p: [1 2 3 4 5]
<class ‘numpy.ndarray’>

Creating Dimentional Arrays

Eg: Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)
print(arr[0]) #to access array element in 0th position
print(arr[-1]) #to acess array element in last position
o/p: [1 2 3 4 5]
1
5

Eg:
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)
print(arr[1,2]) #to access array elements
print(arr.ndim) #to display dimension

o/p: [[1 2 3]
[4 5 6]]
6
2

Object Oriented Programming in Python

Python is a programming language that supports various programming styles, including object-
oriented programming (OOP) through the use of objects and classes. An object is any entity that
has attributes and behaviors.

OOPs Concepts in Python


 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction
Python Class
A class is a collection of objects.

 Classes are created by keyword class.


 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement

Python Objects

The object is an entity that has a state and behavior associated with it.
An object consists of:
 State: It is represented by the attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Syntax: Object Definition

obj = ClassName()
print(obj.atrr)

eg:
\
class Dog:
attr1 = "mammal"
attr2 = "dog"

def fun():
print("I'm a", attr1)
print("I'm a", attr2)

Rodger = Dog()

print(Rodger.attr1)
Rodger.fun()

o/p:
mammal
I'm a mammal
I'm a dog
__init__() method
 The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initializing the object’s state. Like methods, The method is useful to do any initialization you
want to do with your object.

class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

Output:
Hello, my name is Nikhil

Python Encapsulation

Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the
bundling of attributes and methods inside a single class.

Data Abstraction

The abstraction in Python helps a programmer to hide all the irrelevant data of an application
to reduce complexity and increase efficiency

Python Inheritance

Inheritance is a way of creating a new class for using details of an existing class without modifying it.

The newly formed class is a derived class (or child class). Similarly, the existing class is a base class
(or parent class).

Eg:
# base class

class Animal:

def eat(self):

print( "I can eat!")

def sleep(self):

print("I can sleep!")

# derived class

class Dog(Animal):

def bark(self):

print("I can bark! Woof woof!!")

# Create object of the Dog class

dog1 = Dog()

# Calling members of the base class

dog1.eat()

dog1.sleep()

# Calling member of the derived class

dog1.bark();

O/P:
I can eat!
I can sleep!
I can bark! Woof woof!!

Polymorphism

That is, the same entity (method or operator or object) can perform different operations in different
scenarios.
Eg:

class Polygon:

# method to render a shape

def render(self):

print("Rendering Polygon...")

class Square(Polygon):

def render(self):

print("Rendering Square...")

class Circle(Polygon):

def render(self):

print("Rendering Circle...")

# create an object of Square

s1 = Square()

s1.render()

# create an object of Circle

c1 = Circle()

c1.render()

O/P:
Rendering Square…
Rendering Circle…

.
REGULAR EXPRESSION IN PYTHON (Python RegEx)
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be
used to check if a string contains the specified search pattern.

RegEx Module

Python has a built-in package called re, which can be used to work with Regular Expressions.

Import the re module:

Import re

The search() Function

The search() function searches the string for a match, and returns a Match object if there is a match.

If there is more than one match, only the first occurrence of the match will be returned:

Here is the syntax for this function −


re.search(pattern, string)
Here,
Pattern:- This is the regular expression to be matched
String:-This is the string, which would be searched to match the pattern anywhere in the string.

Eg:

#Check if the string starts with "The" and ends with "Spain":

import re

txt = "The rain in Spain"

x = re.search("^The.*Spain$", txt)

if x:

print("YES! We have a match!")

else:

print("No match")

o/p: YES! We have a match!


EXCEPTION HANDLING IN PYTHON
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a
program due to which the program will stop the execution.

Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in
an error. This error does not stop the execution of the program, however, it changes the normal flow
of the program.

Different types of exceptions in python:

In Python, there are several built-in exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:

 SyntaxError: This exception is raised when the interpreter encounters a syntax error in the
code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is not found in the
current scope.
 IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
 ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to divide a number by
zero.
 ImportError: This exception is raised when an import statement fails to find or load a module.
Eg:

# Python program to handle simple runtime error

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

o/p:

Second element =2
An error occurred

You might also like