Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Python - unit 2

Iterations and Comprehensions

Iteration

• Computers are often used to automate repetitive tasks. Repeating identical or


similar tasks without making errors is something that computers do well and
people do poorly.

• Repeated execution of a set of statements is called iteration. Python’s two looping


statements is while and for.

• Although they can handle most repetitive tasks programs need to perform, the need
to iterate over sequences is so common and pervasive that Python provides
additional tools to make it simpler and more efficient.

Iterators: A First Look

In the preceding chapter, I mentioned that the for loop can work on any sequence type

in Python, including lists, tuples, and strings, like this:

>>> for x in [1, 2, 3, 4]: print(x ** 2, end=' ')

...

1 4 9 16

>>> for x in (1, 2, 3, 4): print(x ** 3, end=' ')

...

1 8 27 64

351

>>> for x in 'spam': print(x * 2, end=' ')

...

ss pp aa mm

Actually, the for loop turns out to be even more generic than this—it works on any

iterable object. In fact, this is true of all iteration tools that scan objects from left to right

in Python, including for loops, the list comprehensions we’ll study in this chapter.

The concept of “iterable objects” is relatively recent in Python.


Iterators in Python

Iterator in python is an object that is used to iterate over iterable objects like lists, tuples,
dicts, and sets. The iterator object is initialized using the iter() method. It uses the next()
method for iteration.

1. __iter(iterable)__ method that is called for the initialization of an iterator. This returns an
iterator object

2. next ( __next__ in Python 3) The next method returns the next value for the iterable.
When we use a for loop to traverse any iterable object, internally it uses the iter() method to
get an iterator object which further uses next() method to iterate over. This method raises a
StopIteration to signal the end of the iteration.

How an iterator really works in python

# Here is an example of a python inbuilt iterator

# value can be anything which can be iterate

iterable_value = 'SRMKTR'

iterable_obj = iter(iterable_value)

while True:

try:

# Iterate by calling next

item = next(iterable_obj)

print(item)

except StopIteration:

# exception will happen when iteration will over

break

Output :

K
T

Use of for-in (or for each) style:

This style is used in python containing iterator of lists, dictonary, n dimensional-arrays etc.
The iterator fetches each component and prints data while looping. The iterator is
automatically incremented/decremented in this construct.

# Accessing items using for-in loop

cars = ["Aston", "Audi", "McLaren"]

for x in cars:

print x

Output:

Aston

Audi

McLaren

See this for more examples of different data types.

Indexing using Range function: We can also use indexing using range() in Python.

# Accessing items using indexes and for-in

cars = ["Aston", "Audi", "McLaren"]

for i in range(len(cars)):

print cars[i]

Output:

Aston

Audi

McLaren

Enumerate:

Enumerate is built-in python function that takes input as iterator, list etc and returns a tuple
containing index and data at that index in the iterator sequence. For example,
enumerate(cars), returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and
so on.

# Accessing items using enumerate()

cars = ["Aston" , "Audi", "McLaren "]

for i, x in enumerate(cars):

print (x)

Output :

Aston

Audi

McLaren

Below solution also works.

# Accessing items and indexes enumerate()

cars = ["Aston" , "Audi", "McLaren "]

for x in enumerate(cars):

print (x[0], x[1])

Output :

(0, 'Aston')

(1, 'Audi')

(2, 'McLaren ')

We can also directly print returned value of enumerate() to see what it returns.

# Printing return value of enumerate()

cars = ["Aston" , "Audi", "McLaren "]

print enumerate(cars)

Output :

[(0, 'Aston'), (1, 'Audi'), (2, 'McLaren ')]

zip function (Both iterators to be used in single looping construct):


This function is helpful to combine similar type iterators(list-list or dict- dict etc,) data items
at ith position. It uses the shortest length of these input iterators. Other items of larger
length iterators are skipped. In case of empty iterators, it returns No output.

For example, the use of zip for two lists (iterators) helped to combine a single car and its
required accessory.

# Python program to demonstrate the working of zip

# Two separate lists

cars = ["Aston", "Audi", "McLaren"]

accessories = ["GPS", "Car Repair Kit",

"Dolby sound kit"]

# Combining lists and printing

for c, a in zip(cars, accessories):

print "Car: %s, Accessory required: %s"\

%(c, a)

Output:

Car: Aston, Accessory required: GPS

Car: Audi, Accessory required: Car Repair Kit

Car: McLaren, Accessory required: Dolby sound kit

Comprehensions in Python

Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined. Python supports the following 4 types of comprehensions:

I. List Comprehensions

II. Dictionary Comprehensions

III. Set Comprehensions

IV. Generator Comprehensions

List Comprehensions:
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:

output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List comprehensions
can contain multiple for (nested list comprehensions).

Example #1: Suppose we want to create an output list which contains only the even numbers
which are present in the input list. Let’s see how to do this using for loops and list
comprehension and decide which method suits better.

# Constructing output list WITHOUT

# Using List comprehensions

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_list = []

# Using loop for constructing output list

for var in input_list:

if var % 2 == 0:

output_list.append(var)

print("Output List using for loop:", output_list)

Output:

Output List using for loop: [2, 4, 4, 6]

# Using List comprehensions

# for constructing output list

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

list_using_comp = [var for var in input_list if var % 2 == 0]

print("Output List using list comprehensions:",

list_using_comp)

Output:

Output List using list comprehensions: [2, 4, 4, 6]


Dictionary Comprehensions:

Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example #1: Suppose we want to create an output dictionary which contains only the odd
numbers that are present in the input list as keys and their cubes as values. Let’s see how to
do this using dictionary comprehension.

# Using Dictionary comprehensions

Example #2: Given two lists containing the names of states and their corresponding capitals,
construct a dictionary which maps the states with their respective capitals. Let’s see how to
do this using dictionary comprehension.

# Using Dictionary comprehensions

# for constructing output dictionary

state = ['Gujarat', 'Maharashtra', 'Rajasthan']

capital = ['Gandhinagar', 'Mumbai', 'Jaipur']

dict_using_comp = {key:value for (key, value) in zip(state, capital)}

print("Output Dictionary using dictionary comprehensions:",

dict_using_comp)

Output:

Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur',

'Maharashtra': 'Mumbai',

'Gujarat': 'Gandhinagar'}

Set Comprehensions:

Set comprehensions are pretty similar to list comprehensions. The only difference between
them is that set comprehensions use curly brackets { }. Let’s look at the following example to
understand set comprehensions.

Example #1 : Suppose we want to create an output set which contains only the even
numbers that are present in the input list. Note that set will discard all the duplicate values.
Let’s see how we can do this using set comprehension.
# Using Set comprehensions

# for constructing output set

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

set_using_comp = {var for var in input_list if var % 2 == 0}

print("Output Set using set comprehensions:",

set_using_comp)

Output:

Output Set using set comprehensions: {2, 4, 6}

Generator Comprehensions:

Generator Comprehensions are very similar to list comprehensions. One difference between
them is that generator comprehensions use circular brackets whereas list comprehensions
use square brackets. The major difference between them is that generators don’t allocate
memory for the whole list. Instead, they generate each value one by one which is why they
are memory efficient. Let’s look at the following example to understand generator
comprehension:

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_gen = (var for var in input_list if var % 2 == 0)

print("Output values using generator comprehensions:", end = ' ')

for var in output_gen:

print(var, end = ' ')

Output:

Output values using generator comprehensions: 2 4 4 6

Handling text files Modules

• Python provides inbuilt functions for creating, writing and reading files. There are
two types of files that can be handled in python, normal text files and binary files
(written in binary language,0s and 1s).

• Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
• Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.

In this article, we will be focusing on opening, closing, reading and writing data in a text file.

File Access Modes

• Access modes govern the type of operations possible in the opened file. It refers to
how the file will be used once its opened.

• These modes also define the location of the File Handle in the file. File handle is like a
cursor, which defines from where the data has to be read or written in the file.

There are 6 access modes in python.

Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the
file. If the file does not exists, raises I/O error. This is also the default mode in which file is
opened.

Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.

Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-
written. The handle is positioned at the beginning of the file. Creates the file if the file does
not exists.

Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.

Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the end,
after the existing data.

Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does
not exist. The handle is positioned at the end of the file. The data being written will be
inserted at the end, after the existing data.

Opening a File

It is done using the open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

The file should exist in the same directory as the python program file else, full address of the
file should be written on place of filename.

Note:
• The r is placed before filename to prevent the characters in filename string to be
treated as special character. For example, if there is \temp in the file address, then \t
is treated as the tab character and error is raised of invalid address.

• The r makes the string raw, that is, it tells that the string is without any special
characters. The r can be ignored if the file is in same directory and address is not
being placed.

# Open function to open the file "MyFile1.txt"

# (same directory) in append mode and

file1 = open("MyFile.txt","a")

# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2

file2 = open(r"D:\Text\MyFile2.txt","w+")

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2

Closing a file

close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.

File_object.close()

# Opening and Closing a file "MyFile.txt"

# for object name file1.

file1 = open("MyFile.txt","a")

file1.close()

Writing to a file

There are two ways to write in a file.

write() : Inserts the string str1 in a single line in the text file.

File_object.write(str1)

writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]


Reading from a file

There are three ways to read data from a text file.

read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.

File_object.read([n])

readline() : Reads a line of the file and returns in form of a string.For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of
the line.

File_object.readline([n])

readlines() : Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes

# Program to show various ways to read and

# write data in a file.

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print "Output of Read function is "

print file1.read()

print

# seek(n) takes the file handle to the nth

# bite from the beginning.

file1.seek(0)
print "Output of Readline function is "

print file1.readline()

print

file1.seek(0)

# To show difference between read and readline

print "Output of Read(9) function is "

print file1.read(9)

print

file1.seek(0)

print "Output of Readline(9) function is "

print file1.readline(9) file1.seek(0)

# readlines function

print "Output of Readlines function is "

print file1.readlines()

print

file1.close()

Output:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Readline function is

Hello

Output of Read(9) function is

Hello
Th

Output of Readline(9) function is

Hello

Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending to a file

# Python program to illustrate

# Append vs write mode

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

file1.close()

# Append-adds at last

file1 = open("myfile.txt","a")#append mode

file1.write("Today \n")

file1.close()

file1 = open("myfile.txt","r")

print "Output of Readlines after appending"

print file1.readlines()

print

file1.close()

# Write-Overwrites

file1 = open("myfile.txt","w")#write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt","r")

print "Output of Readlines after writing"


print file1.readlines()

print

file1.close()

Output:

Output of Readlines after appending

['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing

['Tomorrow \n']

Python Classes and Objects

• A class is a user-defined blueprint or prototype from which objects are created.


Classes provide a means of bundling data and functionality together.

• Creating a new class creates a new type of object, allowing new instances of that
type to be made.

• Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods (defined by their class) for modifying their state.

• To understand the need for creating a class let’s consider an example, let’s say you
wanted to track the number of dogs that may have different attributes like breed,
age.

• If a list is used, the first element could be the dog’s breed while the second element
could represent its age. Let’s suppose there are 100 different dogs, then how would
you know which element is supposed to be which? What if you wanted to add other
properties to these dogs? This lacks organization and it’s the exact need for classes.

• Class creates a user-defined data structure, which holds its own data members and
member functions, which can be accessed and used by creating an instance of that
class. A class is like a blueprint for an object.

Some points on Python class:

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-1

# Statement-N

Defining a class –

# Python3 program to

# demonstrate defining

# a class

class Dog:

pass

In the above example, the class keyword indicates that you are creating a class followed by
the name of the class (Dog in this case).

Class Objects

• An Object is an instance of a Class. A class is like a blueprint while an instance is a


copy of the class with actual values.

• It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years
old. You can have many dogs to create many different instances, but without the
class as a guide, you would be lost, not knowing what information is required.

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.
Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.

Example:

Declaring an object –

# Python3 program to

# demonstrate instantiating

# a class

class Dog:

# A simple class

# attribute

attr1 = "mammal"

attr2 = "dog"

# A sample method

def fun(self):

print("I'm a", self.attr1)


print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

Output:

mammal

I'm a mammal

I'm a dog

In the above example, an object is created which is basically a dog named Rodger. This class
only has two class attributes that tell us that Rodger is a dog and a mammal.

The self

• Class methods must have an extra first parameter in the method definition. We do
not give a value for this parameter when we call the method, Python provides it.

• If we have a method that takes no arguments, then we still have to have one
argument.This is similar to this pointer in C++ and this reference in Java.

• When we call a method of this object as myobject.method(arg1, arg2), this is


automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this
is all the special self is about.

__init__ method

• The __init__ method is similar to constructors in C++ and Java. Constructors are used
to initializing the object’s state.

• Like methods, a constructor also contains a collection of statements(i.e. instructions)


that are executed at the time of Object creation.

• It is run as soon as an object of a class is instantiated. The method is useful to do any


initialization you want to do with your object.

# A Sample class with init method

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

Class and Instance Variables

• Instance variables are for data unique to each instance and class variables are for
attributes and methods shared by all instances of the class.

• Instance variables are variables whose value is assigned inside a constructor or


method with self whereas class variables are variables whose value is assigned in the
class.

Defining instance variable using a constructor.

# Python3 program to show that the variables with a value assigned in the class declaration,
are class variables and variables inside methods and constructors are instance variables.

# Class for Dog

class Dog:

# Class Variable

animal = 'dog'

# The init method or constructor

def __init__(self, breed, color):

# Instance Variable

self.breed = breed

self.color = color

# Objects of Dog class

Rodger = Dog("Pug", "brown")


Buzo = Dog("Bulldog", "black")

print('Rodger details:')

print('Rodger is a', Rodger.animal)

print('Breed: ', Rodger.breed)

print('Color: ', Rodger.color)

print('\nBuzo details:')

print('Buzo is a', Buzo.animal)

print('Breed: ', Buzo.breed)

print('Color: ', Buzo.color)

# Class variables can be accessed using class

# name also

print("\nAccessing class variable using class name")

print(Dog.animal)

Output:

Rodger details:

Rodger is a dog

Breed: Pug

Color: brown

Buzo details:

Buzo is a dog

Breed: Bulldog

Color: black

Accessing class variable using class name

dog

Python Exception Handling

• An exception can be defined as an unusual condition in a program resulting in the


interruption in the flow of the program.

• Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the run-time errors that are
unable to handle to Python script. An exception is a Python object that represents an
error

• Python provides a way to handle the exception so that the code can be executed
without any interruption. If we do not handle the exception, the interpreter doesn't
execute all the code that exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption
and give the output. These exceptions are given below:

Common Exceptions

Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard
Python program is given below.

ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local or global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

The problem without handling exceptions

• As we have already discussed, the exception is an abnormal condition that halts the
execution of the program.

• Suppose we have two variables a and b, which take the input from the user and
perform the division of these values.

• What if the user entered the zero as the denominator? It will interrupt the program
execution and through a ZeroDivision exception. Let's see the following example.

Example

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b

print("a/b = %d" %c)

#other code:

print("Hi I am other part of the program")

Output:
Enter a:10

Enter b:0

Traceback (most recent call last):

File "exception-test.py", line 3, in <module>

c = a/b;

ZeroDivisionError: division by zero

The above program is syntactically correct, but it through the error because of unusual
input. That kind of programming may not be suitable or recommended for the projects
because these projects are required uninterrupted execution. That's why an exception-
handling plays an essential role in handling these unexpected exceptions. We can handle
these exceptions in the following way.

Exception handling in python


The try-expect statement

If the Python program contains suspicious code that may throw the exception, we must
place that code in the try block. The try block must be followed with the except statement,
which contains a block of code that will be executed if there is some exception in the try
block.

Syntax

try:

#block of code

except Exception1:

#block of code

except Exception2:
#block of code

#other code

Consider the following example.

Example 1

try:

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b

except:

print("Can't divide with zero")

Output:

Enter a:10

Enter b:0

Can't divide with zero

We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

try:

#block of code

except Exception1:

#block of code

else:

#this code executes if no except block is executed


Consider the following program.

Example 2

try:

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b

print("a/b = %d"%c)

# Using Exception with except statement. If we print(Exception) it will return exception class

except Exception:

print("can't divide by zero")

print(Exception)

else:

print("Hi I am else block")

Output:

Enter a:10
Enter b:0

can't divide by zero

<class 'Exception'>

The except statement with no exception

Python provides the flexibility not to specify the name of exception with the exception
statement.

Consider the following example.

Example

try:

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b;

print("a/b = %d"%c)

except:

print("can't divide by zero")

else:

print("Hi I am else block")

The except statement using with exception variable

We can use the exception variable with the except statement. It is used by using the as
keyword. this object will return the cause of the exception.

Consider the following example:

try:

a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b

print("a/b = %d"%c)

# Using exception object with the except statement

except Exception as e:

print("can't divide by zero")


print(e)

else:

print("Hi I am else block")

Output:

Enter a:10

Enter b:0

can't divide by zero

division by zero

Points to remember

• Python facilitates us to not specify the exception with the except statement.

• We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.

• We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.

• The statements that don't throw the exception should be placed inside the else
block.

Example

try:

#this will throw an exception if the file doesn't exist.

fileptr = open("file.txt","r")

except IOError:

print("File not found")

else:

print("The file opened successfully")

fileptr.close()

Output:

File not found

The try...finally block


• Python provides the optional finally statement, which is used with the try statement.
It is executed no matter what exception occurs and used to release the external
resource. The finally block provides a guarantee of the execution.

• We can use the finally block with the try block in which we can pace the necessary
code, which must be executed before the try statement throws an exception.

The syntax to use the finally block is given below.

Syntax

try:

# block of code

# this may throw an exception

finally:

# block of code

# this will always be executed

Example

try:

fileptr = open("file2.txt","r")

try:

fileptr.write("Hi I am good")

finally:
fileptr.close()

print("file closed")

except:

print("Error")

Output:

file closed

Error

Raising exceptions

• An exception can be raised forcefully by using the raise clause in Python. It is useful
in in that scenario where we need to raise an exception to stop the execution of the
program.

• For example, there is a program that requires 2GB memory for execution, and if the
program tries to occupy 2GB of memory, then we can raise an exception to stop the
execution of the program.

The syntax to use the raise statement is given below.

Syntax

raise Exception_class,<value>

Points to remember

• To raise an exception, the raise statement is used. The exception class name follows
it.

• An exception can be provided with a value that can be given in the parenthesis.

• To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception.

• We can pass the value to an exception to specify the exception type.

Example 1

try:

age = int(input("Enter the age:"))

if(age<18):

raise ValueError

else:

print("the age is valid")


except ValueError:

print("The age is not valid")

Output:

Enter the age:17

The age is not valid

Example 2:

Raise the exception with message

try:

num = int(input("Enter a positive integer: "))

if(num <= 0):

# we can pass the message in the raise statement

raise ValueError("That is a negative number!")

except ValueError as e:

print(e)

Output:

Enter a positive integer: -5

That is a negative number!

User-Defined Exceptions

• Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.

• Here is an example related to RuntimeError. Here, a class is created that is subclassed


from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.

• In the try block, the user-defined exception is raised and caught in the except block.
The variable e is used to create an instance of the class Networkerror.

Sample Code:

class Networkerror(RuntimeError):

def __init__(self, arg):

self.args = arg

So once you defined above class, you can raise the exception as follows −
try:

raise Networkerror("Bad hostname")

except Networkerror,e:

print e.args

List of Standard Exceptions −

Following are the Exception Name & Description

1. Exception - Base class for all exceptions

2. StopIteration - Raised when the next() method of an iterator does not point to any object.

3. SystemExit -Raised by the sys.exit() function.

4. StandardError - Base class for all built-in exceptions except StopIteration and SystemExit.

5. ArithmeticError - Base class for all errors that occur for numeric calculation.

6. OverflowError - Raised when a calculation exceeds maximum limit for a numeric type.

7. FloatingPointError - Raised when a floating point calculation fails.

8. ZeroDivisionError - Raised when division or modulo by zero takes place for all numeric
types.

9. AssertionError - Raised in case of failure of the Assert statement.

10 . AttributeError - Raised in case of failure of attribute reference or assignment.

11. EOFError - Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.

12. ImportError - Raised when an import statement fails.

13. KeyboardInterrupt - Raised when the user interrupts program execution, usually by
pressing Ctrl+c.

14 . LookupError - Base class for all lookup errors.

15. IndexError - Raised when an index is not found in a sequence.

16. KeyError - Raised when the specified key is not found in the dictionary.

17. NameError - Raised when an identifier is not found in the local or global namespace.

18. UnboundLocalError - Raised when trying to access a local variable in a function or


method but no value has been assigned to it.

19. EnvironmentError - Base class for all exceptions that occur outside the Python
environment.
20. IOError - Raised when an input/ output operation fails, such as the print statement or
the open() function when trying to open a file that does not exist.

21 . IOError - Raised for operating system-related errors.

22. SyntaxError - Raised when there is an error in Python syntax.

23. IndentationError - Raised when indentation is not specified properly.

24. SystemError - Raised when the interpreter finds an internal problem, but when this error
is encountered the Python interpreter does not exit.

25. SystemExit - Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.

26. TypeError -Raised when an operation or function is attempted that is invalid for the
specified data type.

27. ValueError - Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.

28. RuntimeError - Raised when a generated error does not fall into any category.

29. NotImplementedError - Raised when an abstract method that needs to be implemented


in an inherited class is not actually implemented.

Regular Expressions

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

RegEx in Python

When you have imported the re module, you can start using regular expressions:

Example

Search the string to see if it 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")

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

Metacharacters

Metacharacters are characters with a special meaning:

Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special characters) "\d"

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "world$"

* Zero or more occurrences "aix*"

+ One or more occurrences "aix+"

{} Exactly the specified number of occurrences "al{2}"

| Either or "falls|stays"

() Capture and group

Special Sequences

A special sequence is a \ followed by one of the characters in the list below, and has a special
meaning:

Character Description

\A Returns a match if the specified characters are at the beginning of the string ex:
"\AThe"
\b Returns a match where the specified characters are at the beginning or at the end
of a word

ex: (the "r" in the beginning is making sure that the string is being treated as a
"raw string") r"\bain"

r"ain\b"

\B Returns a match where the specified characters are present, but NOT at the
beginning (or at the end) of a word

Ex: (the "r" in the beginning is making sure that the string is being treated as a
"raw string") r"\Bain"

r"ain\B"

\d Returns a match where the string contains digits (numbers from 0-9)

EX: "\d"

\D Returns a match where the string DOES NOT contain digits

ex: "\D"

\s Returns a match where the string contains a white space character

"\s"

\S Returns a match where the string DOES NOT contain a white space character
"\S"

\w Returns a match where the string contains any word characters (characters from a to
Z, digits from 0-9, and the underscore _ character)

"\w"

\W Returns a match where the string DOES NOT contain any word characters

"\W"

\Z Returns a match if the specified characters are at the end of the string

"Spain\Z"

Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:

Set Description

[arn] Returns a match where one of the specified characters (a, r, or n) are present

[a-n] Returns a match for any lower case character, alphabetically between a and n

[^arn] Returns a match for any character EXCEPT a, r, and n


[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present

[0-9] Returns a match for any digit between 0 and 9

[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59

[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case
OR upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any
+ character in the string

The findall() Function

The findall() function returns a list containing all matches.

Example

Print a list of all matches:

txt = "The rain in Spain"

x = re.findall("ai", txt)

print(x)

Output:

['ai', 'ai']

The list contains the matches in the order they are found.

If no matches are found, an empty list is returned:

Example

Return an empty list if no match was found:

import re

txt = "The rain in Spain"

#Check if "Portugal" is in the string:

x = re.findall("Portugal", txt)

print(x)

if (x):

print("Yes, there is at least one match!")

else:

print("No match")
Output:

[]

No match

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:

Example

Search for the first white-space character in the string:

import re

txt = "The rain in Spain"

x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())

Output:

The first white-space character is located in position: 3

If no matches are found, the value None is returned:

The split() Function

The split() function returns a list where the string has been split at each match:

Example

Split at each white-space character:

import re

txt = "The rain in Spain"

x = re.split("\s", txt)

print(x)

Output:

['The', 'rain', 'in', 'Spain']

You can control the number of occurrences by specifying the maxsplit parameter:

Split the string only at the first occurrence:

Example
import re

txt = "The rain in Spain"

x = re.split("\s", txt, 1)

print(x)

Output:

['The', 'rain in Spain']

The sub() Function

The sub() function replaces the matches with the text of your choice:

Example

Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"

x = re.sub("\s", "9", txt)

print(x)

Output:

The9rain9in9Spain

Note: You can control the number of replacements by specifying the count parameter:

Example

Replace the first 2 occurrences:

import re

txt = "The rain in Spain"

x = re.sub("\s", "9", txt, 2)

print(x)

Match Object

A Match Object is an object containing information about the search and the result.

Note: If there is no match, the value None will be returned, instead of the Match Object.

Example

Do a search that will return a Match Object:


import re

txt = "The rain in Spain"

x = re.search("ai", txt)

print(x) #this will print an object

Output:

<_sre.SRE_Match object; span=(5, 7), match='ai'>

The Match object has properties and methods used to retrieve information about the
search, and the result:

.span() returns a tuple containing the start-, and end positions of the match.

.string returns the string passed into the function

.group() returns the part of the string where there was a match

Example

Print the position (start- and end-position) of the first match occurrence.

The regular expression looks for any words that starts with an upper case "S":

import re

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.span())

Output:

(12, 17)

Example

Print the string passed into the function:

import re

#The string property returns the search string:

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.string)

Output:

The rain in Spain


Example

Print the part of the string where there was a match.

The regular expression looks for any words that starts with an upper case "S":

import re

#Search for an upper case "S" character in the beginning of a word, and print the word:

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.group())

Output:

Spain

Note: If there is no match, the value None will be returned, instead of the Match Object.

Python Inheritance
• Inheritance allows us to define a class that inherits all the methods and properties
from another class.

• Parent class is the class being inherited from, also called base class.

• Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and a printname
method:

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()

Output:

John Doe

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from the
Person class:

class Student(Person):

pass

Note: Use the pass keyword when you do not want to add any other properties or methods
to the class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")

x.printname()

Output:

Mike Olsen

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to
create a new object.

Example

Add the __init__() function to the Student class:

class Student(Person):

def __init__(self, fname, lname):

#add properties etc.


When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.

Note: The child's __init__() function overrides the inheritance of the parent's __init__()
function.

To keep the inheritance of the parent's __init__() function, add a call to the parent's
__init__() function:

Example

class Student(Person):

def __init__(self, fname, lname):

Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:

Example

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.

Add Properties

Example

Add a property called graduationyear to the Student class:

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into the Student class
when creating student objects. To do so, add another parameter in the __init__() function:

Example
Add a year parameter, and pass the correct year when creating objects:

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

print(x.graduationyear)

OutPut:

2019

Add Methods

Example

Add a method called welcome to the Student class:

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

def welcome(self):

print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

x = Student("Mike", "Olsen", 2019)

x.welcome()

output:

Welcome Mike Olsen to the class of 2019

You might also like