Python Unit -3
Python Unit -3
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.
Code
if (s != o:
^
SyntaxError: invalid syntax
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.
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:
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.
1. try:
2. #Code that might raise an exception
3. except:
4. #Code to replace the exception message
EXCEPTON CONTEXT
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
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
0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable
objects.
Example
3
deque()
The Python deque() is a double-ended queue which allows us to add and remove
elements from both the ends.
Example
Example
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.
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.
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.