Module 2 - Python
Module 2 - Python
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 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.
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
• 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
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
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict[“model”])
• 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.
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])
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
Eg:
string1 = "hello"
string2 = "hello, world“
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string1!=string4)
• 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
• 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
Using append()
• The append() method adds an item at the end of the list. For example,
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]
Eg:
Items=[‘car’,jeep’,’bus’]
Items[2]=‘auto’
Print(items)
o/p:
[‘car’,’jeep’,’auto’]
III. Remove an Item 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++’]
• 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
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
• 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”,”}
• 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
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
def my_function(country):
print("I am from " + country)
my_function("Sweden")
• 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
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.
Use a module
import mymodule
mymodule.greeting("John")
Variables in Module
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)
• 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)
• 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"
}
PACKAGES IN PYTHON
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
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".
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.
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
print(a)
o/p: [1 2 3 4 5]
print(np.__version__)
o/p: 1.25.0
print(arr)
print(type(arr))
o/p: [1 2 3 4 5]
<class ‘numpy.ndarray’>
import numpy as np
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
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
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.
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.
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:
# 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):
def sleep(self):
# derived class
class Dog(Animal):
def bark(self):
dog1 = Dog()
dog1.eat()
dog1.sleep()
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:
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
def render(self):
print("Rendering Square...")
class Circle(Polygon):
def render(self):
print("Rendering Circle...")
s1 = Square()
s1.render()
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 re
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:
Eg:
#Check if the string starts with "The" and ends with "Spain":
import re
x = re.search("^The.*Spain$", txt)
if x:
else:
print("No match")
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.
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:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
o/p:
Second element =2
An error occurred