Python Programming Chapter 4
Python Programming Chapter 4
Python Arrays
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:-
OUTPUT:-
Some of the data types are mentioned below which will help in creating an
array of different data types.
CODE:-
# Python program to demonstrate
# Adding Elements to a Array
OUTPUT:-
Array before insertion : 1 2 3
CODE:-
# Python program to demonstrate
# accessing of element from list
OUTPUT:-
CODE:-
print ("\r")
print("\r")
OUTPUT:-
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(:).
# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end =" ")
OUTPUT:-
Initial Array:
1 2 3 4 5 6 7 8 9 10
CODE:-
print ("\r")
OUTPUT:-
print ("\r")
OUTPUT:-
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:-
OUTPUT:-
CODE:-
OUTPUT:-
a = marks / 0
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:-
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
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.
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:
try:
fun(3)
fun(5)
OUTPUT:-
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:-
OUTPUT:-
-5.0
a/b result in 0
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
CODE:-
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
OUTPUT:-
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:-
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
NameError: Hi there
Class
Objects
Polymorphism
Encapsulation
Inheritance
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.
CODE:-
# parent class
class Person(object):
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
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
OUTPUT:-
886012
My name is A
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.
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.")
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:-
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
# 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)
OUTPUT:-
HelloCocsitHello