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

Python Unit -3

This document covers exception handling and collections in Python, explaining the difference between syntax errors and exceptions, and how to handle exceptions using try and except blocks. It also introduces the Python collections module, detailing various collection types such as namedtuple, OrderedDict, defaultdict, Counter, and deque, along with their functionalities. Additionally, it discusses the characteristics of Python sets and how to create them.

Uploaded by

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

Python Unit -3

This document covers exception handling and collections in Python, explaining the difference between syntax errors and exceptions, and how to handle exceptions using try and except blocks. It also introduces the Python collections module, detailing various collection types such as namedtuple, OrderedDict, defaultdict, Counter, and deque, along with their functionalities. Additionally, it discusses the characteristics of Python sets and how to create them.

Uploaded by

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

Unit – III

Exception Handling and Collections

Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the program.
An error in Python might be either an error in the syntax of an expression or a Python
exception. We will see what an exception is. Also, we will see the difference between a
syntax error and an exception in this tutorial. Following that, we will learn about trying and
except blocks and how to raise exceptions and make assertions. After that, we will see
the Python exceptions list.

What is an Exception?
An exception in Python is an incident that happens while executing a program that causes
the regular course of the program's commands to be disrupted. When a Python code
comes across a condition it can't handle, it raises an exception. An object in Python that
describes an error is called an exception.

When a Python code throws an exception, it has two options: handle the exception
immediately or stop and quit.

Exceptions versus Syntax Errors


When the interpreter identifies a statement that has an error, syntax errors occur. Consider
the following scenario:

Code

1. #Python code after removing the syntax error


2. string = "Python Exceptions"
3.
4. for s in string:
5. if (s != o:
6. print( s )
Output:

if (s != o:
^
SyntaxError: invalid syntax

Role Exception is a custom exception created automatically


by OutSystems from each role available in your module. For example, if you
create a role named BackofficeUser in a module, OutSystems automatically
creates a Role Exception named Not BackofficeUser in the same module.
Exception handling in Python
Before going into the topic, we need to understand about errors and exceptions in
python and the difference between these two words.

First things first, there are errors-two types of them - Syntax errors and logical errors.
A syntax error occurs when the programmer did not follow the predefined syntax rules of
a particular entity in the code.

If the compiler finds a syntax mistake, it terminates the program and raises the
error. We need to fix it.

Logical errors are the mistakes the programmer makes in the logic of the code. These
are not raised; instead, the mistake is to be understood when the code does not meet
the purpose or problem. These are to be searched, found, and edited by the programmer
and are hard to find.

Now coming to the concept of exceptions:

An exception is an unexpected error raised at the time of execution (not at


compilation). These are not dangerous to the code; there are methods in python to
handle these exceptions.

Example: If we try to divide a number by 0, the compiler won't detect it as the syntax is
correct. At the time of execution, the exception will be raised.

Code:

1. a = 3
2. print(a/0)
Output:

Traceback (most recent call last):


File "D:\Programs\python\exception_ex.py", line 2, in
print(a/0)
ZeroDivisionError: division by zero

The "Exception" is the base class for all the exceptions. There is a whole exception
hierarchy defined in python. You can check it out online.

We can handle exceptions using try and except blocks. We can also raise user-defined
exceptions, which will be discussed further in the article.

Using try and except statements to catch exceptions:


Exceptions usually occur unexpectedly and disturb the execution of the whole
code. Hence, we catch these exceptions and handle them for the execution to go
smoothly.

And how do we do that?


o The part of the code on which the programmer doubts that it may cause an
exception is kept in the try block.
o If the doubt comes true and an exception is found, we write the handling code inside
the "except" block.
o What happens here is that the code we write inside the "except" block replaces
the exception/error message that usually gets printed when the exception is found.
o In this way, the execution flow is not disturbed, and the exception is handled.
Syntax:

1. try:
2. #Code that might raise an exception
3. except:
4. #Code to replace the exception message

EXCEPTON CONTEXT

1. ZeroDivisionError If we try to perform division by 0

If the result of an operation is too big to be


2. OverflowError
presented

If we try to access an index of a sequence that is


3. IndexError
invalid

If we try to call an attribute (function object), its


4. AttributeError
type is unsupported.

If a function in python reaches the end of the file


5. EOFError
without reading any data at all.

If we try to access a key in a dictionary that is


6. KeyError
invalid or does not even exist

7. IOError If we give a wrong file name or incorrect location.

To catch a particular Exception (try with multiple except


statements)
Suppose the code has a chance of raising multiple exceptions. The programmer needs to
replace different exceptions with different code, i.e., if they want to handle each
exception differently, there is an option for this too.

o One try statement can have multiple catch statements.


o We can catch a particular type of exception by mentioning the exception beside except
in the except block.

Python Collection Module


The Python collection module is defined as a container that is used to store collections of
data, for example - list, dict, set, and tuple, etc. It was introduced to improve the
functionalities of the built-in collection containers.

Python collection module was first introduced in its 2.4 release.

There are different types of collection modules which are as follows:

namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position
in the tuple. It was used to eliminate the problem of remembering the index of each field
of a tuple object in ordinary tuples.

Examples

1. pranshu = ('James', 24, 'M')


2. print(pranshu)
Output:

('James', 24, 'M')


OrderedDict()
The Python OrderedDict() is similar to a dictionary object where keys maintain the order
of insertion. If we try to insert key again, the previous value will be overwritten for that key.

Example

1. import collections
2. d1=collections.OrderedDict()
3. d1['A']=10
4. d1['C']=12
5. d1['B']=11
6. d1['D']=13
7.
8. for k,v in d1.items():
9. print (k,v)
Output:

A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-
in dict class. It provides all methods provided by dictionary but takes the first argument as
a default data type.

Example

1. from collections import defaultdict


2. number = defaultdict(int)
3. number['one'] = 1
4. number['two'] = 2
5. print(number['three'])
Output:

0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable
objects.

Example

1. from collections import Counter


2. c = Counter()
3. list = [1,2,3,4,5,7,8,5,9,6,10]
4. Counter(list)
5. Counter({1:5,2:4})
6. list = [1,2,4,7,5,1,6,7,6,9,1]
7. c = Counter(list)
8. print(c[1])
Output:

3
deque()
The Python deque() is a double-ended queue which allows us to add and remove
elements from both the ends.

Example

1. from collections import deque


2. list = ["x","y","z"]
3. deq = deque(list)
4. print(deq)
Output:

deque(['x', 'y', 'z'])


Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single list.
The linked dictionary stores in the list and it is public and can be accessed by the map
attribute. Consider the following example.

Example

1. from collections import ChainMap


2. baseline = {'Name': 'Peter', 'Age': '14'}
3. adjustments = {'Age': '14', 'Roll_no': '0012'}
4. print(list(ChainMap(adjustments, baseline)))
Output:

['Name', 'Age', 'Roll_no' ]


UserDict Objects
The UserDict behaves as a wrapper around the dictionary objects. The dictionary can be
accessed as an attribute by using the UserDict object. It provides the easiness to work
with the dictionary.

It provides the following attribute.

data - A real dictionary used to store the contents of the UserDict class.

UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we want
to add new functionality to the lists. It provides the easiness to work with the dictionary.

It provides the following attribute.

data - A real list is used to store the contents of the User class.

UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can be
accessed as an attribute by using the UserString object. It provides the easiness to work
with the dictionary.

It provides the following attribute.

data - A real str object is used to store the contents of the UserString class.

Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set,
i.e., we cannot directly access any element of the set by the index. However, we can print
them all together, or we can get the list of elements by looping through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by
the passed sequence.

Example 1: Using curly braces


1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sun
day"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

You might also like