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

Python Programming Chapter 4

fghj;fgl

Uploaded by

meenapawar894
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Python Programming Chapter 4

fghj;fgl

Uploaded by

meenapawar894
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Python Programming Chapter 4

 Python Arrays

An array is a collection of items stored at contiguous memory locations. The


idea is to store multiple items of the same type together.

This makes it easier to calculate the position of each element by simply adding
an offset to a base value, i.e., the memory location of the first element of the
array (generally denoted by the name of the array).

For simplicity, we can think of an array a fleet of stairs where on each step is
placed a value (let’s say one of your friends). Here, you can identify the
location of any of your friends by simply knowing the count of the step they
are on. Array can be handled in Python by a module named array.

They can be useful when we have to manipulate only a specific data type
values. A user can treat lists as arrays. However, user cannot constraint the type
of elements stored in a list. If you create arrays using the array module, all
elements of the array must be of the same type.

Creating a Array
Array in Python can be created by importing array
module. array(data_type, value_list) is used to create an array with data type
and value list specified in its arguments.

CODE:-

# Python program to demonstrate


# Creation of Array

# importing "array" for array creations


import array as arr

# creating an array with integer type


a = arr.array('i', [1, 2, 3])

# printing original array


print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()

By R.S. Jadhav Page 1


Python Programming Chapter 4

# creating an array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array


print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")

OUTPUT:-

The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3

Some of the data types are mentioned below which will help in creating an
array of different data types.

Adding Elements to a Array


Elements can be added to the Array by using built-in insert() function. Insert is
used to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given
index of array. append() is also used to add the value mentioned in its
arguments at the end of the array.

CODE:-
# Python program to demonstrate
# Adding Elements to a Array

# importing "array" for array creations


import array as arr

# array with int type


a = arr.array('i', [1, 2, 3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3):

By R.S. Jadhav Page 2


Python Programming Chapter 4

print (a[i], end =" ")


print()

# inserting array using


# insert() function
a.insert(1, 4)

print ("Array after insertion : ", end =" ")


for i in (a):
print (i, end =" ")
print()

# array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3):
print (b[i], end =" ")
print()

# adding an element using append()


b.append(4.4)

print ("Array after insertion : ", end =" ")


for i in (b):
print (i, end =" ")
print()

OUTPUT:-
Array before insertion : 1 2 3

Array after insertion : 1 4 2 3

Array before insertion : 2.5 3.2 3.3

Array after insertion : 2.5 3.2 3.3 4.4

By R.S. Jadhav Page 3


Python Programming Chapter 4

Accessing elements from the Array


In order to access the array items refer to the index number. Use the index
operator [ ] to access an item in a array. The index must be an integer.

CODE:-
# Python program to demonstrate
# accessing of element from list

# importing array module


import array as arr

# array with int type


a = arr.array('i', [1, 2, 3, 4, 5, 6])

# accessing element of array


print("Access element is: ", a[0])

# accessing element of array


print("Access element is: ", a[3])

# array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

# accessing element of array


print("Access element is: ", b[1])

# accessing element of array


print("Access element is: ", b[2])

OUTPUT:-

Access element is: 1

Access element is: 4

Access element is: 3.2

Access element is: 3.3

By R.S. Jadhav Page 4


Python Programming Chapter 4

Removing Elements from the Array


Elements can be removed from the array by using built-in remove() function
but an Error arises if element doesn’t exist in the set. Remove() method only
removes one element at a time, to remove range of elements, iterator is
used. pop() function can also be used to remove and return an element from the
array, but by default it removes only the last element of the array, to remove
element from a specific position of the array, index of the element is passed as
an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the
searched element.

CODE:-

# Python program to demonstrate


# Removal of elements in a Array

# importing "array" for array operations


import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 5])

# printing original array


print ("The new created array is : ", end ="")
for i in range (0, 5):
print (arr[i], end =" ")

print ("\r")

# using pop() to remove element at 2nd position


print ("The popped element is : ", end ="")
print (arr.pop(2))

# printing array after popping


print ("The array after popping is : ", end ="")
for i in range (0, 4):
print (arr[i], end =" ")

print("\r")

By R.S. Jadhav Page 5


Python Programming Chapter 4

# using remove() to remove 1st occurrence of 1


arr.remove(1)

# printing array after removing


print ("The array after removing is : ", end ="")
for i in range (0, 3):
print (arr[i], end =" ")

OUTPUT:-

The new created array is : 1 2 3 1 5

The popped element is : 3

The array after popping is : 1 2 1 5

The array after removing is : 2 1 5

Slicing of a Array
In Python array, there are multiple ways to print the whole array with all the
elements, but to print a specific range of elements from the array, we use Slice
operation. Slice operation is performed on array 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 array in reverse order, use [::-1].
CODE:-

# Python program to demonstrate


# slicing of elements in a Array

# importing array module


import array as arr

# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)
print("Initial Array: ")

By R.S. Jadhav Page 6


Python Programming Chapter 4

for i in (a):
print(i, end =" ")

# Print elements of a range


# using Slice operation
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)

# Print elements from a


# pre-defined point to end
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)

# Printing elements from


# beginning till end
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

OUTPUT:-

Initial Array:

1 2 3 4 5 6 7 8 9 10

Slicing elements in a range 3-8:

array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end:

array('i', [6, 7, 8, 9, 10])

Printing all elements using slice operation:

array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

By R.S. Jadhav Page 7


Python Programming Chapter 4

Searching element in a Array


In order to search an element in the array we use a python in-
built index() method. This function returns the index of the first occurrence of
value mentioned in arguments.

CODE:-

# Python code to demonstrate


# searching an element in array

# importing array module


import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array


print ("The new created array is : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")

print ("\r")

# using index() to print index of 1st occurrenece of 2


print ("The index of 1st occurrence of 2 is : ", end ="")
print (arr.index(2))

# using index() to print index of 1st occurrenece of 1


print ("The index of 1st occurrence of 1 is : ", end ="")
print (arr.index(1))

OUTPUT:-

The new created array is : 1 2 3 1 2 5

The index of 1st occurrence of 2 is : 1

The index of 1st occurrence of 1 is : 0

By R.S. Jadhav Page 8


Python Programming Chapter 4

Updating Elements in a Array


In order to update an element in the array we simply reassign a new value to
the desired index we want to update.
CODE:-
# Python code to demonstrate
# how to update an element in array

# importing array module


import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array


print ("Array before updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")

print ("\r")

# updating a element in a array


arr[2] = 6
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
print()

# updating a element in a array


arr[4] = 8
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")

OUTPUT:-

Array before updation : 1 2 3 1 2 5

Array after updation : 1 2 6 1 2 5

By R.S. Jadhav Page 9


Python Programming Chapter 4

Array after updation : 1 2 6 1 8 5

 Python Exception Handling


Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors
are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax
in the code. It leads to the termination of the program.

CODE:-

# initialize the amount variable


amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

By R.S. Jadhav Page 10


Python Programming Chapter 4

OUTPUT:-

File "f:\COCSIT\B.Sc(CS)- TY(Python)\main2.py", line 6

if(amount > 2999)

SyntaxError: expected ':'

Exceptions: Exceptions are raised when the program is syntactically correct,


but the code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

CODE:-

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)

OUTPUT:-

Traceback (most recent call last):

File "f:\COCSIT\B.Sc(CS)- TY(Python)\main2.py", line 5, in <module>

a = marks / 0

ZeroDivisionError: division by zero

In the above example raised the ZeroDivisionError as we are trying to divide a


number by 0.
Note: Exception is the base class for all the exceptions in Python

Try and Except Statement – Catching Exceptions

By R.S. Jadhav Page 11


Python Programming Chapter 4

Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound
and handle the corresponding exception.

CODE:-

# Python program to handle simple runtime error


#Python 3

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")

OUTPUT:-

Second element = 2

An error occurred

In the above example, the statements that can cause the error are placed inside
the try statement (second print statement in our case). The second print
statement tries to access the fourth element of the list which is not there and
this throws an exception. This exception is then caught by the except statement.

Catching Specific Exception

A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed. For
example, we can add IndexError in the above code. The general syntax for
adding specific exceptions are –
try:
By R.S. Jadhav Page 12
Python Programming Chapter 4

# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exception in Python

CODE:-
# Program to handle multiple errors with one
# except statement
# Python 3

def fun(a):
if a < 4:

# throws ZeroDivisionError for a = 3


b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

OUTPUT:-

ZeroDivisionError Occurred and Handled

If you comment on the line fun(3), the output will be

By R.S. Jadhav Page 13


Python Programming Chapter 4

NameError Occurred and Handled


The output above is so because as soon as python tries to access the value of b,
NameError occurs.

Try with Else Clause

In python, you can also use the else clause on the try-except block which must
be present after all the except clauses. The code enters the else block only if the
try clause does not raise an exception.
Example: Try with else clause

CODE:-

# Program to depict else clause with try-except


# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

OUTPUT:-

-5.0

a/b result in 0

Finally Keyword in Python


Python provides a keyword finally, which is always executed after the try and
except blocks. The final block always executes after normal termination of try
block or after try block terminates due to some exception.
Syntax:

By R.S. Jadhav Page 14


Python Programming Chapter 4

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)

CODE:-

# Program to depict else clause with try-except


# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:

By R.S. Jadhav Page 15


Python Programming Chapter 4

print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

OUTPUT:-

Can't divide by zero

This is always executed

Raising Exception
The raise statement allows the programmer to force a specific exception to
occur. The sole argument in raise indicates the exception to be raised. This
must be either an exception instance or an exception class (a class that derives
from Exception).

CODE:-

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised
or not

The output of the above code will simply line printed as “An exception” but a
Runtime error will also occur in the last due to the raise statement in the last
line. So, the output on your command line will look like

OUTPUT:-

An exception

By R.S. Jadhav Page 16


Python Programming Chapter 4

Traceback (most recent call last):

File "f:\COCSIT\B.Sc(CS)- TY(Python)\tempCodeRunnerFile.py", line 4, in


<module>

raise NameError("Hi there") # Raise Error

NameError: Hi there

 Python OOPs Concepts

In Python, object-oriented Programming (OOPs) is a programming paradigm


that uses objects and classes in programming. It aims to implement real-world
entities like inheritance, polymorphisms, encapsulation, etc. in the
programming. The main concept of OOPs is to bind the data and the functions
that work on that together as a single unit so that no other part of the code can
access this data.

Main Concepts of Object-Oriented Programming (OOPs)

 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance

By R.S. Jadhav Page 17


Python Programming Chapter 4

Inheritance
Inheritance is the capability of one class to derive or inherit the properties from
another class. The class that derives properties is called the derived class or
base class and the class from which the properties are being derived is called
the base class or parent class. The benefits of inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without
modifying it.
 It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class
A.

Example: Inheritance in Python

CODE:-

# Python code to demonstrate how parent constructors


# are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):

By R.S. Jadhav Page 18


Python Programming Chapter 4

self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))

# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('A', 886012, 200000, "Intern")

# calling a function of the class Person using


# its instance
a.display()
a.details()

OUTPUT:-

886012

My name is A

By R.S. Jadhav Page 19


Python Programming Chapter 4

IdNumber: 886012

Post: Intern

We have created two classes i.e. Person (parent class) and Employee (Child
Class). The Employee class inherits from the Person class. We can use the
methods of the person class through employee class as seen in the display
function in the above code. A child class can also modify the behavior of the
parent class as seen through the details() method.

What is object class?


Like Java Object class, in Python (from version 3.x), object is root of all
classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2.x, “class Test(object)” creates a class with object as parent (called
new style class) and “class Test” creates old style class (without object parent).

Subclassing (Calling constructor of parent class)


A child class needs to identify which class is its parent class. This can be done
by mentioning the parent class name in the definition of the child class.
Eg: class subclass_name (superclass_name):
___
___

Polymorphism
Polymorphism simply means having many forms. For example, we need to
determine if the given species of birds fly or not, using polymorphism we can
do this using a single function.

CODE:-
class Bird:

def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some
cannot.")

By R.S. Jadhav Page 20


Python Programming Chapter 4

class sparrow(Bird):

def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

OUTPUT:-

There are many types of birds.

Most of the birds can fly but some cannot.

There are many types of birds.

Sparrows can fly.

There are many types of birds.

Ostriches cannot fly.

Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables
By R.S. Jadhav Page 21
Python Programming Chapter 4

and methods directly and can prevent the accidental modification of data. To
prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is
member functions, variables, etc.

CODE:-
# Python program to
# demonstrate private members

# Creating a Base class


class Base:
def __init__(self):
self.a = "HelloCocsitHello"
self.__c = "HelloCocsitHello"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

By R.S. Jadhav Page 22


Python Programming Chapter 4

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

OUTPUT:-
HelloCocsitHello

By R.S. Jadhav Page 23

You might also like