0% found this document useful (0 votes)
2 views29 pages

UNIT 2_PythonProgramming (1)

This document covers data structures in Python, including strings, lists, tuples, dictionaries, and sets, along with exception handling. It explains string manipulation, list operations, and the differences between lists and tuples, emphasizing their mutability and methods. Additionally, it provides examples of built-in functions and methods for each data structure.

Uploaded by

rameshapositive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

UNIT 2_PythonProgramming (1)

This document covers data structures in Python, including strings, lists, tuples, dictionaries, and sets, along with exception handling. It explains string manipulation, list operations, and the differences between lists and tuples, emphasizing their mutability and methods. Additionally, it provides examples of built-in functions and methods for each data structure.

Uploaded by

rameshapositive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT – II DATA STRUCTURES AND PACKAGES

Strings –List – Tuples – Dictionaries–Sets – Exception Handling: Built-in Exceptions – User-


defined exception– Modules and Packages.

Strings

The string can be defined as the sequence of characters represented in the quotation
marks. In python, we can use single, double, or triple quotes to define a string.

String handling in python is a straightforward task since there are various inbuilt functions and
operators provided.In the case of string handling, the operator + is used to concatenate two
strings as the operation "hello"+" python" returns "hello python". Strings in Python are
immutable. You can’t change a string in-place, but you can copy parts of strings to another string
to get the same effect.

The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".

A substring (a part of a string) froma string extracted by using a slice.A slice is defined by using
square brackets, a start offset, an end offset, and an optional step size. Some of these can be
omitted. The slice will include characters from offset start to one before end.

1. [:] extracts the entire sequence from start to end.

2. [ start :] specifies from the start offset to the end.

3. [: end ] specifies from the beginning to the end offset minus 1.

4. [ start : end ] indicates from the start offset to the end offset minus 1.

5. [ start : end : step ] extracts from the start offset to the end offset minus 1, skipping
characters by step.

Example

str1 = 'Good Morning' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[3]) #printing 3rd character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

output

Go
d
Good MorningGood Morning
Good Morning how are you

Strings Built-in Functions


name = "Welcome Good How Morning How Are You"
name1 = " hai "

print(name1.lstrip(' ')) # Output: "hai "


print(name1.rstrip(' ')) # Output: " hai"
print(name1.strip(' ')) # Output: "hai"
print(max(name1)) # Output: "i"

print(name[4:-5]) # Output: "ome Good How Morning How Ar"


print(name.count("how", 0, len(name))) # Output: 0 (case-sensitive)
print(name.endswith("you", 0, len(name))) # Output: False (case-sensitive)
print(name.find("how", 0, len(name))) # Output: -1 (case-sensitive)
print(name.isalnum()) # Output: False (spaces make it non-alphanumeric)
print(name.islower()) # Output: False
print(name.upper()) # Output: "WELCOME GOOD HOW MORNING HOW ARE YOU"
print(name.istitle()) # Output: True (each word starts with uppercase)

s = "-"
l = ["a", "b", "c"]
print(s.join(l)) # Output: "a-b-c"

print(max(name)) # Output: "w" (max character based on ASCII value)


print(name.swapcase()) # Output: "wELCOME gOOD hOW mORNING hOW aRE yOU"
print(name.title()) # Output: "Welcome Good How Morning How Are You"
print(name.replace("Good", "bad")) # Output: "Welcome bad How Morning How Are You"
print(name.split(" ")) # Output: ['Welcome', 'Good', 'How', 'Morning', 'How', 'Are', 'You']

Lists

Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size.
They are also mutable—unlike strings, lists can be modified in place by assignment to offsets as
well as a variety of list method calls.A list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas. The same value can occur more than once in a list.
Empty list is created with list = []

a_list = ['a', 'b', 'mpilgrim', 'z', 'example']


print(a_list) # Output: ['a', 'b', 'mpilgrim', 'z', 'example']

print(a_list[0]) # Output: 'a'


print(a_list[4]) # Output: 'example'
print(a_list[-1]) # Output: 'example'
print(a_list[-3]) # Output: 'mpilgrim'
The above code works in the following manner

1. First, define a list of five items. Note that they retain their original order.
2. A list can be used like a zero-based array. The first item of any non-empty list is always
a_list[0].
3. The last item of this five-item list is a_list[4], because lists are always zero-based.
4. A negative index accesses items from the end of the list counting backwards. The last item of
any non-empty list is always a_list[-1].
5. If the negative index is confusing to you, think of it this way: a_list[-n] == a_list[len(a_list) -
n]. So in this list, a_list[-3] == a_list[5 - 3] == a_list[2].

Slicing a List

A range of items in a list can be accesses by using the slicing operator (:). Part of a list, called a
“slice”is obtained by specifying two indices. The return value is a new list containing all the
items of the list, in order, starting with the first slice index (in this case a_list[1]), up to but not
including the second slice index (in this case a_list[3]).

a_list = ['a', 'b', 'mpilgrim', 'z', 'example']

print(a_list) # Output: ['a', 'b', 'mpilgrim', 'z', 'example']


print(a_list[1:3]) # Output: ['b', 'mpilgrim']
print(a_list[1:-1]) # Output: ['b', 'mpilgrim', 'z']
print(a_list[0:3]) # Output: ['a', 'b', 'mpilgrim']
print(a_list[:3]) # Output: ['a', 'b', 'mpilgrim']
print(a_list[3:]) # Output: ['z', 'example']
print(a_list[:]) # Output: ['a', 'b', 'mpilgrim', 'z', 'example']

Adding Items to a List

There are four ways to add items to a list.

1. The + operator concatenates lists to create a new list. A list can contain any number of items;
there is no size limit (other than available memory).
2. The append() method adds a single item to the end of the list.
4. Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list
has methods that operate on it. The extend() method takes one argument, a list, and appends each
of the items of the argument to the original list.
5. The insert() method inserts a single item into a list. The first argument is the index of the first
item in the list that will get bumped out of position. List items do not need to be unique; for
example, there are now two separate items with the value 'Ω': the first item, a_list[0], and the last
item, a_list[6].
a_list = ['a']
a_list = a_list + [2.0, 3]
print(a_list) # Output: ['a', 2.0, 3]

a_list.append(True)
print(a_list) # Output: ['a', 2.0, 3, True]

a_list.extend(['four', 'Ω'])
print(a_list) # Output: ['a', 2.0, 3, True, 'four', 'Ω']

a_list.insert(0, 'Ω')
print(a_list) # Output: ['Ω', 'a', 2.0, 3, True, 'four', 'Ω']

Append: Adds its argument as a single element to the end of a list. The length of the list
increases by one.

Extend(): Iterates over its argument and adding each element to the list and extending the list.
The length of the list increases by number of elements in it’s argument

Removing Items from a List

Lists can expand and contract automatically. There are several different ways to remove items
from a list. The elements of a list is removed by using del function. Elements can also removed
from the List 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 set, but
by default it removes only the last element of the set, to remove element from a specific position
of the List, index of the element is passed as an argument to the pop() method.

Method 1 : Using del statement


# Initialize the list
a_list = ['a', 'b', 'new', 'mpilgrim', 'new']

# Access the second element (index 1)


print(a_list[1]) # Output: 'b'

# Delete the element at index 1


del a_list[1]

# Print the updated list


print(a_list) # Output: ['a', 'new', 'mpilgrim', 'new']

# Access the new second element (index 1)


print(a_list[1]) # Output: 'new'
Method 2 : Using remove() function

# Initialize the list


a_list = ['a', 'b', 'new', 'mpilgrim', 'new']

# Remove the first occurrence of 'new'


a_list.remove('new')

# Print the updated list


print(a_list) # Output: ['a', 'b', 'mpilgrim', 'new']

# Remove the next occurrence of 'new'


a_list.remove('new')

# Print the final list


print(a_list) # Output: ['a', 'b', 'mpilgrim']

Method 2 : Using pop() function


When called without arguments, the pop() list method removes the last item in the list and
returns the value it remove.

# Initialize the list


a_list = ['a', 'b', 'new', 'mpilgrim']

# Pop the last element (default behavior)


print(a_list.pop()) # Output: 'mpilgrim'

# Print the updated list


print(a_list) # Output: ['a', 'b', 'new']

# Pop the element at index 1 ('b')


print(a_list.pop(1)) # Output: 'b'

# Print the updated list


print(a_list) # Output: ['a', 'new']

# Pop the last element ('new')


print(a_list.pop()) # Output: 'new'

# Pop the remaining element ('a')


print(a_list.pop()) # Output: 'a'

# Print the final empty list


print(a_list) # Output: []
Python List Built-in Methods

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

Pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python List Built-in functions

Python provides the following built-in functions which can be used with the lists.
Tuples
A tuple is an immutable list. A tuple can not be changed in any way once it is created. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different
comma-separated values.
Lists have methods like append(), extend(), insert(), remove(), and pop(). Tuples have none of
these methods. Tuples are faster than lists. The operators like concatenation (+), repetition (*),
Membership (in) works in the same way as they work with the list. We can store list inside tuple
or tuple inside the list up to any number of level.Tuples use less space. Tuples can be used as a
dictionary keys.Empty list is created with list = ().

Creating a tuple with one element is a bit tricky.Having one element within parentheses is not
enough. We will need a trailing comma to indicate that it is, in fact, a tuple.

# Creating a tuple having one element

# Creating a tuple with a single element (note the comma)


my_tuple = ("hello",)
print(type(my_tuple)) # Output: <class 'tuple'>

# Creating another tuple with multiple elements


a_tuple = ("a", "b", "mpilgrim", "z", "example")
print(a_tuple) # Output: ('a', 'b', 'mpilgrim', 'z', 'example')
Access Tuple Elements

There are various ways in which we can access the elements of a tuple.

1. Indexing
Function Description
cmp(list1, list2) It compares the elements of both the lists.
len(list) It is used to calculate the length of the list.
max(list) It returns the maximum element of the list.
min(list) It returns the minimum element of the list.
list(seq) It converts any sequence to the list.

We can use the index operator [] to access an item in a tuple where the index starts from 0.So, a
tuple having 6 elements will have indices from 0 to 5. Trying to access an element outside of
tuple (for example, 6, 7,...) will raise an IndexError.The index must be an integer; so we cannot
use float or other types. This will result in TypeError.

my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'

print(my_tuple[5]) # 't'
2. Negative Indexing
Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the
second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete
or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items


# TypeError: 'tuple' object doesn't support item deletion
# delmy_tuple[3]

# Can delete an entire tuple


delmy_tuple

# NameError: name 'my_tuple' is not defined


print(my_tuple)

Other Tuple Operations


1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.
my_tuple = ('a','p','p','l','e',)

# In operation
# Output: True
print('a' in my_tuple)

# Output: False
print('b' in my_tuple)

# Not in operation
# Output: True
print('g' not in my_tuple)
2. Iterating Through a Tuple
Using a for loop we can iterate through each item in a tuple.
for name in ('John','Kate'):
print("Hello",name)
# Output:
# Hello John
# Hello Kate

The following are true about tuples


1. You can’t add elements to a tuple. Tuples have no append () or extend () method.

2. You can’t remove elements from a tuple. Tuples have no remove () or pop() method. To
explicitly remove an entire tuple, del statement is used.

3. You can find elements in a tuple, since this doesn’t change the tuple.

4. You can also use the in operator to check if an element exists in the tuple.

Comparison between lists and tuples

List Tuple

The literal syntax of list is shown by the The literal syntax of the tuple is shown by the
[]. ().

The List is mutable. The tuple is immutable.

The List has the variable length. The tuple has the fixed length.

The list provides more functionality than The tuple provides less functionality than the
tuple. list.

The list Is used in the scenario in which The tuple is used in the cases where we need to
we need to store the simple collections store the read-only collections i.e., the value of
the items cannot be changed. It can be used as
with no constraints where the value of the
the key inside the dictionary.
items can be changed.

Sets

set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets. The elements of the set cannot be duplicate. 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.

The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set.

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().It can have any number of items and they may be of different
types (integer, float, tuple, string etc.).But a set cannot have a mutable element, like list, set
or dictionary, as its element.Sets can be used to filter duplicates out of other collections

# Set of integers

my_set = {1, 2, 3}

print(my_set) # Output: {1, 2, 3}

# Set of mixed datatypes

my_set = {1.0, "Hello", (1, 2, 3)}


print(my_set) # Output: {1.0, 'Hello', (1, 2, 3)}

Creating Set

Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python. To make a set without any elements we use the set() function without any argument.

# initialize a with {}
a = {}
# check data type of a
print(type(a))
# Output: <class 'dict'>

# initialize a with set()


a = set()

# check data type of a


print(type(a))
# Output: <class 'set'>

Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Example:

thisset={"apple", "banana", "cherry"}


for x in thisset:
print(x)

Adding or modifying the items to the set

Once a set is created, you cannot change its items, but you can add new items.Single element can
be added using the add() method and multiple elements can be added using the update() method.
The update() method can take tuples, lists, strings or other sets as its argument. In all cases,
duplicates are avoided.

Example for add() & Update()

# Define a set
thisset = {"apple", "banana", "cherry"}

# Add a single element to the set


thisset.add("orange")
print(thisset) # Output will include "orange" in an unordered manner

# Re-initialize the set


thisset = {"apple", "banana", "cherry"}

# Add multiple elements to the set using update()


thisset.update(["orange", "mango", "grapes"])
print(thisset) # Output will include "orange", "mango", and "grapes" in an unordered manner
Removing Items

A particular item can be removed from set using methods, discard() and remove().The only
difference between the two is that, while using discard() if the item does not exist in the set, it
remains unchanged. But remove() will raise an error in such condition. Similarly, an item can be
removed and returned using the pop() method. All items from a set is removed
using clear().The del keyword will delete the set completely.

Example
# Initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set) # Output: {1, 3, 4, 5, 6}

# Discard an element (4)


my_set.discard(4)
print(my_set) # Output: {1, 3, 5, 6}

# Remove an element (6)


my_set.remove(6)
print(my_set) # Output: {1, 3, 5}

# Discard an element (2) that is not in the set


my_set.discard(2)
print(my_set) # Output: {1, 3, 5}

Set Operations
Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. This can be do with operators or methods. Union is performed
using | operator or the method union().Union of A and B is a set of all elements from both
sets.Intersection is performed using & operator or the method intersection().Intersection
of A and B is a set of elements that are common in both sets.Difference is performed
using - operator or method difference(). Difference of A and B (A - B) is a set of elements that
are only in A but not in B. Similarly, B - A is a set of element in B but not in A.Symmetric
difference is performed using ^ operator or method symmetric_difference().Symmetric
Difference of A and B is a set of elements in both A and B except those that are common in both.

Example:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A|B)
print(A&B)
print(A-B)
print(A^B)

Output
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}

Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.

Dictionaries

Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary
must be unique and of immutable data type such as Strings, Integers and tuples, but the key-
values can be repeated and be of any type.

Creating a Dictionary

In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any datatype
and can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created
by just placing to curly braces{}.

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary:")

print(Dict)

# Creating a Dictionary with Integer Keys

Dict = {1: 'Arun', 2: 'Deepa', 3: 'Keerthi'}


print("\nDictionary with the use of Integer Keys:")

print(Dict)

# Creating a Dictionary with Mixed Keys

Dict = {'Name': 'Arun', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys:")

print(Dict)

# Creating a Dictionary using dict() method

Dict = dict({1: 'Arun', 2: 'Keerthi', 3: 'Deepa'})

print("\nDictionary with the use of dict():")

print(Dict)

# Creating a Dictionary with each item as a pair

Dict = dict([(1, 'Arun'), (2, 'Deepa')])

print("\nDictionary with each item as a pair:")


print(Dict)

OutPut:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Arun', 2: 'Deepa', 3: 'Keerthi'}
Dictionary with the use of Mixed Keys:
{'Name': 'Arun', 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: 'Arun', 2: 'Keerthi', 3: 'Deepa'}
Dictionary with each item as a pair:
{1: 'Arun', 2: 'Deepa'}
Accessing elements from a Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.There is also a method called get() that will also help in accessing the element from a
dictionary.

# Creating a dictionary
Dict = {1: 'arun', 'name': 'kalai', 3: 'kumar'}

# Accessing an element using a key


print("Accessing an element using key:")
print(Dict['name']) # Output: kalai

# Accessing an element using a key


print("Accessing an element using key:")
print(Dict[1]) # Output: arun

# Accessing an element using the get() method


print("Accessing an element using get():")
print(Dict.get(3)) # Output: kumar

Removing Elements from Dictionary

In Python Dictionary, deletion of keys can be done by using the del keyword. Using del
keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other
functions like pop() and popitem() can also be used for deleting specific values and arbitrary
values from a Dictionary. All the items from a dictionary can be deleted at once by
using clear() method.

# Creating a dictionary of squares

squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Remove a particular item using pop() and return its value

print(squares.pop(4)) # Output: 16

# Print the dictionary after removal

print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25}


# Remove an arbitrary item using popitem() (removes and returns the last key-value pair in
Python 3.7+)

print(squares.popitem()) # Output: (5, 25) (or another random pair in older versions)

# Print the dictionary after popitem()

print(squares) # Output: {1: 1, 2: 4, 3: 9} (may vary based on Python version)

# Delete a particular item using del

del squares[3]

print(squares) # Output: {1: 1, 2: 4}

# Remove all items using clear()

squares.clear()

print(squares) # Output: {}

# Delete the dictionary itself

del squares

# Trying to print squares now would throw an error as it no longer exists.

# Uncommenting the line below will raise a NameError:


# print(squares) # NameError: name 'squares' is not defined

Output:

16

{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)

{1: 1, 2: 4, 3: 9}

{1: 1, 2: 4}
{}

Dictionary Methods
METHODS DESCRIPTION

copy() They copy() method returns a shallow copy of the dictionary.

clear() The clear() method removes all items from the dictionary.

Removes and returns an element from a dictionary having the


pop() given key.

Removes the arbitrary key-value pair from the dictionary and


popitem() returns it as tuple.

get() It is a conventional method to access a value for a key.

dictionary_name.values(
) returns a list of all the values available in a given dictionary.

str() Produces a printable string representation of a dictionary.

update() Adds dictionary dict2’s key-values pairs to dict

setdefault() Set dict[key]=default if key is not already in dict

keys() Returns list of dictionary dict’s keys

items() Returns a list of dict’s (key, value) tuple pairs

has_key() Returns true if key in dictionary dict, false otherwise

Create a new dictionary with keys from seq and values set to
fromkeys() value.

type() Returns the type of the passed variable.

cmp() Compares elements of both dict.

Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is not
executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after the that.

Errors can also occur at runtime and these are called exceptions. They occur, for example, when
a file we try to open does not exist (FileNotFoundError), dividing a number by zero
(ZeroDivisionError), module we try to import is not found (ImportError) etc.

Whenever these type of runtime error occur, Python creates an exception object. If not handled
properly, it prints a traceback to that error along with some details about why that error occurred.
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.
Python Built-in Exceptions

Exception Cause of Error

AssertionError Raised when assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

OSError Raised when system operation causes system related error.

OverflowError Raised when result of an arithmetic operation is too large to be


represented.

Raised when a weak reference proxy is used to access a garbage


ReferenceError collected referent.

RuntimeError Raised when an error does not fall under any other category.

Raised by next() function to indicate that there is no further item to be


StopIteration returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

Raised when a function or operation is applied to an object of incorrect


TypeError type.

Raised when a reference is made to a local variable in a function or


UnboundLocalError method, but no value has been bound to that variable.

UnicodeError Raised when a Unicode-related encoding or decoding error occurs.

UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateErro
r Raised when a Unicode-related error occurs during translating.

Raised when a function gets argument of correct type but improper


ValueError value.

ZeroDivisionError Raised when second operand of division or modulo operation is zero.

The try and except Block: Handling Exceptions


The try and except block in Python is used to catch and handle exceptions. Python executes code
following the try statement as a “normal” part of the program. The code that follows
the except statement is the program’s response to any exceptions in the preceding try clause.
In try block you can write the code which is suspicious to raise an exception, and
in except block, you can write the code which will handle this exception.

Syntax

try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

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.A try clause can
have any number of except clause to handle them differently, but only one will be executed in
case an exception occurs.

Syntax

try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Declaring multiple exceptions


The python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions. This
can be achieved by writing names of exception classes in except clause seperated by comma.
Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code
else:
#block of code

try-finally clause

The try statement in Python can have an optional finally clause. In case if there is any code
which you want to be executed, whether exception occurs or not, then that code can be placed
inside the finally block. When an exception occurs, the control immediately goes to finally block
and all the lines in finally block gets executed first. After that the control goes to except block to
handle exception.

Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code
finally:
# block of code
# this will always be executed

Raising exceptions

An exception can be raised by using the raise clause in python. The syntax to use the raise
statement is given below.

syntax
raise Exception_class,<value>

Example

try:

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

if b == 0:

raise ArithmeticError # Removed unnecessary semicolon

else:

print("a / b =", a / b)

except ArithmeticError:

print("The value of b can't be 0")

except ValueError:

print("Invalid input! Please enter integer values.") # Added exception handling for non-
integer input

Output:

1.Enter a: 10

Enter b: 2

a / b = 5.0

2. Enter a: 10

Enter b: 0

The value of b can't be 0

3. Enter a: hello

Invalid input! Please enter integer values.

User-Defined Exceptions

It is possible to define our own exception in Python. The built-in and user-defined exceptions in
Python using try, except and finally statements.
In Python, users can define such exceptions by creating a new class. This exception class has to
be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are
also derived from this class.

# Define Python user-defined exceptions

class Error(Exception):

"""Base class for other exceptions"""

pass

class ValueTooSmallError(Error):

"""Raised when the input value is too small"""

pass

class ValueTooLargeError(Error):

"""Raised when the input value is too large"""

pass

# Number to be guessed

number = 10

while True:

try:

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

if i_num < number:

raise ValueTooSmallError # Corrected class name


elif i_num > number:

raise ValueTooLargeError # Corrected class name

break # Exit loop when guessed correctly

except ValueTooSmallError:

print("This value is too small, try again!")

print()

except ValueTooLargeError:

print("This value is too large, try again!")

print()

print("Congratulations! You guessed it correctly.")

Python Modules
A module is a file containing Python definitions and statements. A module can define functions,
classes and variables. A module can also include runnable code. Python modules are .py files
that consist of Python code. Any Python file can be referenced as a module.Grouping related
code into a module makes the code easier to understand and use.
# calc.py - A simple calculator module

def add(x, y):


"""Returns the sum of x and y"""
return x + y

def subtract(x, y):


"""Returns the difference of x and y"""
return x - y

The import statement

We can use any Python source file as a module by executing an import statement in some other
Python source file.
The import has the following syntax
import module1[, module2[,... moduleN]
Python's from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax
from modname import name1[, name2[, ... nameN]]
It is also possible to import all the names from a module into the current namespace by using the
following import statement −
from modname import *
This provides an easy way to import all the items from a module into the current namespace.
When interpreter encounters an import statement, it imports the module if the module is present
in the search path. A search path is a list of directories that the interpreter searches for importing
a module. For example, to import the module calc.py, we need to put the following command at
the top of the script :

main.py

from calc import subtract # Corrected module name

import calc

print(calc.add(10, 2)) # Added parentheses


print(subtract(78, 45)) # This works because subtract() was imported directly

Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.

Math module
Python Math module provides access to the mathematical functions. These include trigonometric
functions, representation functions, logarithmic functions, angle conversion functions, etc. So,
we can do many complex mathematical operations with the help of the Python Math functions
eg

import math

number = -2.34

print("The given number is:", number)

print("Floor value is:", math.floor(number))

print("Ceiling value is:", math.ceil(number))


print("Absolute value is:", math.fabs(number))

Output
The given number is: -2.34
Floor value is: -3
Ceiling value is: -2
Absolute value is: 2.34

Random module
The random module gives access to various useful functions and one of them being able to
generate random numbers, which is randint().randint() is an inbuilt function of the random
module in Python
Syntax :

# Python program explaining the work of randint() function

# Import the random module

import random

# Generates a random number between a given positive range

r1 = random.randint(0, 10)

print("Random number between 0 and 10 is:", r1)

# Generates a random number between a given negative range

r2 = random.randint(-10, -1)

print("Random number between -10 and -1 is:", r2)

# Generates a random number between a positive and a negative range

r3 = random.randint(-5, 5)
print("Random number between -5 and 5 is:", r3)
Output:

Random number between 0 and 10 is: 7

Random number between -10 and -1 is: -3


Random number between -5 and 5 is: 2

Packages in Python
Packages are namespaces which contain multiple packages and modules themselves. A
package is a collection of Python modules, i.e., a package is a directory of Python modules
containing an additional __init__.py file. The __init__.py distinguishes a package from a
directory that just happens to contain a bunch of Python scripts. Packages can be nested to any
depth, provided that the corresponding directories contain their own __init__.py file.

When you import a module or a package, the corresponding object created by Python is always
of type module. This means that the distinction between module and package is just at the file
system level. Note, however, when you import a package, only variables/functions/classes in the
__init__.py file of that package are directly visible, not sub-packages or modules.

Packages allow for a hierarchical structuring of the module namespace using dot notation. In
the same way that modules help avoid collisions between global variable names, packages help
avoid collisions between module names. Packages can contain nested subpackages to arbitrary
depth.

__init__.py

The package folder contains a special file called __init__.py, which stores the package's content.
It serves two purposes:

1. The Python interpreter recognizes a folder as the package if it contains __init__.py file.
2. __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from above modules available when this package
is imported. Note that __init__.py is essential for the folder to be recognized by Python as a
package.

The __init__.py file is normally kept empty. However, it can also be used to choose specific
functions from modules in the package folder and make them available for import.
Steps to Create a Python Package

1. Create a directory and give it your package's name.


2. Put your functions in it.
3. Create a __init__.py file in the directory

importing packages

# Importing modules (Example placeholders)


from package_name import *
from package_name import module_name1, module_name2
from package_name import module_name3 as alt_name

# Defining the Student class


class Student:
no_of_students = 0 # Class variable (Fixed variable name format)

def __init__(self, name, age):


self.name = name
self.age = age
Student.no_of_students += 1 # Increments count for each student instance

def display_details(self):
print("Name:", self.name, ", Age:", self.age)

# Creating instances of Student class


s1 = Student("Jothi", 37)
s2 = Student("Senthil", 35)
s3 = Student("Keerthi", 27)

# Calling the display_details() method for each student


s1.display_details()
s2.display_details()
s3.display_details()

# Printing total number of students


print("Total Number of Students:", Student.no_of_students)

Output:

Name: Jothi , Age: 37


Name: Senthil , Age: 35
Name: Keerthi , Age: 27
Total Number of Students: 3

You might also like