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

Lab Manual of Python Fh25.Docx

The document is a lab manual for a Python course (Lab Code: ITL404) for SE Information Technology students. It outlines the college and department vision and mission, lab objectives, outcomes, prerequisites, hardware and software requirements, detailed syllabus, and a list of experiments. The manual aims to equip students with practical skills in Python programming, covering topics such as data types, control flow, object-oriented programming, and data visualization.

Uploaded by

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

Lab Manual of Python Fh25.Docx

The document is a lab manual for a Python course (Lab Code: ITL404) for SE Information Technology students. It outlines the college and department vision and mission, lab objectives, outcomes, prerequisites, hardware and software requirements, detailed syllabus, and a list of experiments. The manual aims to equip students with practical skills in Python programming, covering topics such as data types, control flow, object-oriented programming, and data visualization.

Uploaded by

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

LAB MANUAL OF

PYTHON LAB
Lab Code: ITL404

Class: SE Information Technology


Semester: IV (Rev-2019 ‘C’ Scheme)

Subject In-Charge H.O.D. I.T.

Mr. Nilesh Mali Dr. Pradip Mane

VPPCOE&VA -DM-IT -FF-09 REVISION 00 29/12/2023


College Vision
● To provide an environment to educate, encourage and explore students by facilitating innovative
research, entrepreneurship, opportunities and employability to achieve social and professional goals.

College Mission

● To foster entrepreneurship & strengthen industry institute interaction to enhance career opportunities
for the employability of students.
● To encourage collaborations with industries and academic institutes in terms of projects & internships
by creating area for Research and Development.
● To build up appropriate moral and ethical skills and to promote holistic development of students
through various academic, social and cultural activities

Department Vision

● To impart quality education in the field of Information Technology to meet the challenging needs of the
society and industry.

Department Mission

● To provide quality education to students by including Problem Solving, Teamwork and Leadership
Skills to achieve their goals in the field of Information Technology.
● To develop skilled IT professionals with moral principles and empower them in lifelong learning.
● To educate students for global development including entrepreneurship, employability and the ability
to apply technology to real life problems.

Program Educational Objectives (PEO)

● Graduates will be successful with sound foundation in engineering fundamentals, trending technologies
and entrepreneurship.
● Graduates will be able to identify and solve real world problems.
● Graduates will become ingenious and responsible citizens by demonstrating ethics with nurtured
professional attitude
Program Specific Outcomes (PSO)
● Develop efficient IT based solutions by applying and integrating various domains like Artificial
Intelligence, IoT, Computer Networks and Security to solve real time problems.
● Apply technical knowledge in the field of Information Technology to achieve successful career and to
pursue higher studies for future endeavors.

Program Outcomes (POs)


● Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
● Problem analysis: Identity, formulate complex engineering problems reaching substantiated
conclusions using principles of Computer Engineering.
● Design / development of solutions: Design / develop solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the society.
● Conduct investigations of complex problems: Use knowledge for the design of experiments,
analysis, interpretation of data, and synthesis of the information to provide valid conclusions.
● Modern tool usage: Create, select and apply appropriate techniques and modern engineering
tools, including predictions and modeling to complex engineering activities with an
understanding of the limitations.
● The engineer and society: Apply the knowledge to assess social issues and the
responsibilities relevant to engineering practices.
● Environment and sustainability: Understand the impact of the professional engineering solutions
in social and environmental contexts, and demonstrate the knowledge for sustainable development.
● Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
● Individual and teamwork: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
● Communication: Communicate effectively such as being able to comprehend and write
effective reports and design documentation, make effective presentations.
● Project management and finance: Demonstrate knowledge and understanding of the
engineering and management skills and apply the skills to manage projects effectively.
● Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Lab Objectives:
The Lab experiments aims:
1. Basics of python including data types, operator, conditional statements, looping statements, input and
output functions in Python.
2. List, tuple, set, dictionary, string, array and functions.
3. Object Oriented Programming concepts in python.
4. Concepts of modules, packages, multithreading and exception handling.
5. File handling, GUI & database programming.
6. Data visualization using Matplotlib, Data analysis using Pandas and Web programming using Flask.

Lab Outcomes:
On successful completion, of course, learner/student will be able to:
1. Understand the structure, syntax, and semantics of the Python language.
2. Interpret advanced data types and functions in python.
3. Illustrate the concepts of object-oriented programming as used in Python.
4. Create Python applications using modules, packages, multithreading and exception
handling.
5. Gain proficiency in writing File Handling programs ,also create GUI applications
and evaluate database operations in python.
6. Design and Develop cost-effective robust applications using the latest Python trends
and technologies.
Prerequisite: Structured Programming Approach & Java Programming Lab

Hardware & Software Requirements:

Hardware Requirements:

1. Intel Dual core

Processor or higher

2. Minimum 2 GB RAM

3. Minimum 40 GB Hard disk

4. Network interface card

Software Requirements:

1. Windows or Linux Desktop OS

2. Python 3.6 or higher

3. Notepad ++

4. Python IDEs like IDLE, Pycharm, Pydev, Netbeans or Eclipse

5. Mysql.
DETAILED SYLLABUS:

LO
Sr. No. Detailed Content Hours
Mapping

0 Python IDE installation and environment setup. 02

1 Introduction, Features, Python building blocks Identifiers, 08 LO1


Keywords, Indention, Variables and Comments,
Basic data types (Numeric, Boolean, Compound).
Operators: Arithmetic, comparison, relational, assignment, logical,
bitwise, membership, identity operators, operator precedence
Control flow statements: Conditional statements
( if,if else,nested if).
Looping in Python (while loop, for loop, nested loops)
Loop manipulation using continue, pass, break.
Input/output Functions, Decorators, Iterators and Generators.

2 Lists: a) Defining lists, accessing values in list, deleting values in 09 LO1,L


list, updating lists O2
b) Basic list operations
c) Built-in list functions Tuples: a) Accessing values in Tuples,
deleting values in Tuples, and updating Tuples b) Basic
Tuple operations c) Built-in Tuple functions Dictionaries: a)
Accessing values in Dictionary, deleting values in Dictionary, and
updating Dictionary b) Basic Dictionary operations c) Built-in
Dictionary functions Sets: a) Accessing values in Set, deleting
values in Set, updating Sets b) Basic Set operations, c) Built-in Set
functions Strings: a) String initialization, Indexing, Slicing
,Concatenation, Membership & Immutability b) Built-in String
functions
Arrays: a) Working with Single dimensional Arrays: Creating,
importing, Indexing, Slicing, copying and processing array arrays.
b) Working with Multi-dimensional Arrays using Numpy:
Mathematical operations, Matrix operations, aggregate and other
Built-in function
Functions: a) Built-in functions in python b) Defining function,
calling function, returning values, passing parameters c) Nested
and Recursive functions d) Anonymous Functions
(Lambda, Map, Reduce, Filter).
3 Overview of Object-oriented programming ,Creating Classes and 08 LO1
Objects, Self-Variable, Constructors, Inner class, Static method, LO3
Namespaces.
Inheritance: Types of Inheritance (Single, Multiple, Multi-level,
Hierarchical), Super() method, Constructors in inheritance, operator
overloading, Method overloading, Method
overriding, Abstract class, Abstract method, Interfaces in Python.

4 Modules: Writing modules, importing objects from modules, 06 LO1


Python built-in modules (e.g. Numeric and Mathematical module, LO4
Functional Programming module, Regular Expression module),
Namespace and Scoping.
Packages: creating user defined packages and importing packages.
Multi-threading: process vs thread, use of threads, types of threads,
creating threads in python, thread synchronization, deadlock of
threads.
Exception handling: Compile time errors, Runtime errors,
exceptions, types of exception, try statement, except block, raise
statement, Assert statement, User-Defined Exceptions.

5 File Handling: Opening file in different modes, closing a file, 09 LO1


writing to a file, accessing file contents using standard library LO4
functions, reading from a file read (), readline (), readlines (),
Renaming and Deleting a file, File Exceptions, Pickle in Python.
Graphical user interface (GUI): different GUI tools in python
(Tkinter, PyQt, Kivy etc.),
Working with containers, Canvas, Frame, Widgets (Button, Label,
Text, Scrollbar, Check button, Radio button, Entry, Spinbox,
Message etc.) Connecting GUI with databases to perform CRUD
operations. (on supported databases like SQLite, MySQL, Oracle,
PostgreSQL etc.).

6 Visualization using Matplotlib: Matplotlib with Numpy, working 10 LO1


with plots (line plot, bar graph, histogram, scatter plot, area plot, pie LO6
chart etc.), working with multiple figures.
Data manipulation and analysis using Pandas:
Introduction to Pandas, importing data into Python, series, data
frames, indexing data frames, basic operations with data frame,
filtering, combining and merging data frames, Removing
Duplicates. SciPy: Linear algebra functions using Numpy and
Scipy. Web programming: Introduction to Flask, Creating a Basic
Flask Application, Build a Simple REST API using Flask
Text Books:
1. Dr. R. Nageswara Rao," Core Python Programming", Dreamtech Press, Wiley Publication
2. M. T. Savaliya, R. K. Maurya, "Programming through Python", StarEdu Solutions.
3. E Balagurusamy, "Introduction to computing and problem-solving using python", McGraw Hill
Publication.

References:
1. Zed A. Shaw, "Learn Python 3 the Hard Way", Zed Shaw's Hard Way Series.
2. Martin C. Brown," Python: The Complete Reference", McGraw-Hill Publication.
3. Paul Barry." Head First Python", 2nd Edition, O'Reilly Media, Inc.
List of Experiments

Sr. No. Experiment Name LO

Write a python program to implement Basic data types, Operators, LO1


1
expressions and Input Output Statements

2 Write a python program to implement Control flow statements: LO1


Conditional statements (if , if…else , nested if)

3 Write a python program to implement Looping in Python (while LO1


loop, for loop, nested loop)
LO1
4 Write a python program to implement Different List and List
LO2
operations.
LO1
5 Write a python program to implement Tuple operations using
LO2
Built-in functions.
LO1
6 Write a python program to implement Built-in Set and String
LO2
functions
LO1
7 Write a python program to implement Functions (Built-in, User
LO2
Defined, Anonymous).
LO1
8 Write a python program to implement Classes, object, Static
LO3
method, constructors and Inner class.

LO1
9 Write a python program to implement different types of Inheritance.
LO3
LO1
10 Write a python program to implement Polymorphism with Method
LO3
overloading and Method Overriding.

LO1
11 Write a python program to implement Abstract class, Abstract
LO3
method and Interfaces in Python.
LO1
12 Write a python program to implement User-defined
LO4
modules/packages and import them in a program
LO1
13 Write a python program to implement multithreaded application in
LO4
python

LO1
14 Write a python program to create a menu driven application which
LO4
should cover all the built-in exceptions in python.
LO1
15 Write a python program to implement File Handling operations in
LO5
Python

LO1
16 Write a python program to implement GUI Application using
LO5
Tkinter
LO1
17 Write a python program to implement different types of plots using
LO6
Numpy and Matplotlob.
Experiment No. 1
Aim: To study about Basic data types, Operators, expressions and Input Output Statements in Python.

Theory:

1. Basic Data Types:

Figure 1: Data Types in Python


Python supports various fundamental data types:
● Integers (int): Whole numbers without any decimal point. Example: ‘x = 5’
● Floats (float): Numbers with a decimal point. Example: ‘y = 3.14’
● Strings (str): Sequences of characters enclosed in single or double quotes.
Example: ‘text = "Hello, World!" ’
● Boolean (bool): Represents truth values ‘True’ or ‘False’.
● Dictionaries (dict): Dictionaries are used to store data values in key:value pairs.
Eg: d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
● List (list): Lists in Python are like arrays in C, but lists can contain data of different types. The
things put away in the rundown are isolated with a comma (,) and encased inside square
sections [].
Eg: [1, 'hi', 'Python', 2]
● Tuple (tuple): In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of
items from various data types. A parenthetical space () separates the tuple's components from
one another.
Eg: tup = ("hi", "Python", 2)

2. Operators:
Arithmetic Operators:
● + (Addition)
● - (Subtraction)
● * (Multiplication)
● / (Division)
● // (Floor Division - rounds down to the nearest whole number)
● % (Modulus - returns the remainder of division)
● ** (Exponentiation)

Comparison Operators:
● == (Equal to)
● != (Not equal to)
● > (Greater than)
● < (Less than)
● >= (Greater than or equal to)
● <= (Less than or equal to)

Logical Operators:

● and (Logical AND)


● or (Logical OR)
● not (Logical NOT)

3. Expressions:
Expressions are combinations of values, variables, and operators that result in a value when
evaluated. For example:
x=5
y = 10
result = x + y * 2
Here, the result will hold the value 25.

4. Input-Output Statements:
Input:
input() function is used to take user input.
Example:
name = input("Enter your name: ")
Output:
print() function is used to display output to the console.
Example:
print("Hello,", name)

Example:
# Calculate the area of a rectangle
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print("The area of the rectangle is:", area)

Conclusion: Hence we have successfully studied Basic data types, Operators, expressions and Input
Output Statements in Python.
Experiment No. 2
Aim: To implement Control flow statements: Conditional statements (if, if…else, nested if).
Theory:
Conditional Statements
Conditional statements in Python allow you to control the flow of your code based on certain conditions.
The primary conditional statements include if, if…else, and nested if statements.

1. if Statement:
The if statement checks a condition and executes a block of code only if that condition is True.
Syntax:
if condition:
# Code block to execute if condition is True

2. if…else Statement:
The if…else statement allows you to execute one block of code if the condition is True, and another block
of code if the condition is False.
Syntax:
if condition:
# Code block to execute if condition is True
else:
# Code block to execute if condition is False

3. Nested if Statements:
You can also have if statements inside other if statements, creating nested structures. This allows for more
complex decision-making based on multiple conditions.
Syntax:
if condition1:
# Executes when condition1 is True
if condition2:
# Executes when condition1 and condition2 are True
else:
# Executes
when condition1 is True but condition2 is False
statement(s)
else:
# Executes when condition1 is False statement(s)

Conclusion: Hence we have successfully implemented Control flow statements : Conditional statements
(if , if…else , nested if).
Experiment No. 3
Aim: To implement Looping in Python: (while loop, for loop, nested loop).

Theory:

Looping Constructs in Python


Loops in Python are control structures that allow you to execute a block of code repeatedly based on a
specified condition. There are mainly two types of loops in Python: while loop and for loop. Additionally,
nested loops involve using one loop inside another loop.

1. while Loop:
The while loop in Python repeatedly executes a block of code as long as a specified condition is true.
Syntax:
while condition:
# code block to be executed

2. for Loop:
The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or any
iterable object.
Syntax:
for element in sequence:
# code block to be executed

3. Nested Loops:
Nested loops in Python refer to using one loop inside another loop. This allows for more complex
iterations.
Syntax:
for outer_item in outer_sequence:
for inner_item in inner_sequence:
# code block to be executed

Conclusion: Hence we have successfully implemented Looping in Python : (while loop , for loop, nested
loop).
Experiment No. 4

Aim: To implement Different List and List operations.

Theory:

List Operations:
List operations in Python refer to various actions or manipulations that can be performed on lists, which
are ordered, mutable collections of elements. These operations allow for the modification, retrieval,
manipulation, and analysis of list data structures.

1. Creating Lists: Define a sequence of elements enclosed in square brackets ‘[ ]’ to create a list.
Example:
# Creating a list
my_list = [1, 2, 3, 4, 5]

2. Appending and Extending Lists: Add single elements or merge another list at the end of an existing
list.
Example:
# Appending elements to a list
my_list.append(6)

# Extending a list with another list


another_list = [7, 8, 9]
my_list.extend(another_list)

3. Accessing Elements: Retrieve specific elements by index or obtain subsets using slicing.
Example:
# Accessing elements by index
element = my_list[2]

# Slicing a list
sliced_list = my_list[1:4]
4. Inserting and Removing Elements: Insert elements at specified positions or remove elements by value
or index.
Example:
# Inserting elements at specific positions
my_list.insert(3, 10) # Inserting 10 at index 3

# Removing elements by value


my_list.remove(4)

# Removing elements by index


del my_list[0] # Deleting the element at index 0

5. List Manipulation: Reverse order, sort elements, and count occurrences within a list.
Example:
# Reversing a list
my_list.reverse()

# Sorting a list
my_list.sort()

# Counting occurrences of an element in a list


count = my_list.count(2)

6. List Information: Determine the length, check element existence, and find the index of elements
within a list.
Example:
# Finding the length of a list
length = len(my_list)

# Finding the index of an element


index = my_list.index(5)

Conclusion: Hence we have successfully implemented Different Lists and List operations.
Experiment No. 5

Aim: To Implement Tuple Operations using Built-in functions.

Theory:

Tuple Operations:

Tuple operations in Python involve various actions or manipulations that can be performed on tuples,
which are ordered, immutable collections of elements. Unlike lists, tuples cannot be modified after
creation, so operations on tuples focus on accessing, retrieving information, and performing certain
transformations without altering the original tuple.

1. Creating Tuples: Construct an immutable sequence of elements enclosed in parentheses.


Example:
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)

2. Accessing Elements: Retrieve specific elements by index or obtain subsets using slicing.
Example:
# Accessing elements by index
element = my_tuple[2]

# Slicing a tuple
sliced_tuple = my_tuple[1:4]

3. Tuple Information: Determine the length, check element existence, and find the index of elements
within a tuple.
Example:
# Finding the length of a tuple
length = len(my_tuple)

# Checking for existence of an element


existence = 3 in my_tuple
# Finding the index of an element
index = my_tuple.index(5)

4. Counting Occurrences: Count the number of times a specific element appears within a tuple.
Example:
# Counting occurrences of an element in a tuple
count = my_tuple.count(2)

5. Tuple Operations (Immutable): As tuples are immutable, direct modification operations such as
appending, removing, or sorting elements are not feasible.

6. Join Tuple: In Python, you can join tuples using the + operator for concatenation or by creating a new
tuple that includes elements from multiple tuples. Since tuples are immutable, joining them creates a new
tuple containing elements from the original tuples.
Example/Syntax:
Using the ‘+’ Operator for Concatenation:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

# Using the + operator to join tuples


joined_tuple = tuple1 + tuple2

print(joined_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')

Creating a New Tuple with Elements from Multiple Tuples:


tuple3 = ('x', 'y')
tuple4 = (4, 5)

# Creating a new tuple by including elements from multiple tuples


joined_tuple_2 = tuple3 + tuple4

print(joined_tuple_2) # Output: ('x', 'y', 4, 5)

Conclusion: Hence we have successfully implemented Tuple Operations using Built-in function.
Experiment No. 6

Aim: To Implement Built-in Set and String functions


Theory:
Built-in Set functions:
1. Creating a set: Creates an empty set or converts an iterable to a set.
Syntax: set_name = {element1, element2, ...}

2.add(): Adds an element to a set.


Syntax:
set_name.add(element)

3.remove() and discard():


remove() removes a specified element, raising an error if not present.
discard() removes a specified element without an error if not present.
Syntax:
set_name.remove(element)
set_name.discard(element)

4.union():
Returns a new set with unique elements from both sets.
Syntax:
set_result = set1.union(set2, ...)

5.intersection():
Returns a new set with common elements from two sets.
Syntax:
set_result = set1.intersection(set2, ...)

Built-in String Functions:


1. len(): Returns the length of the string.
Syntax:
len(string)

2. str.upper(): Converts all characters in a string to uppercase.


Syntax:
string.upper()

3. str.lower(): Converts all characters in a string to lowercase.


Syntax:
string.lower()

4. str.capitalize(): Capitalizes the first character of the string.


Syntax:
string.capitalize()

5. str.title(): Converts the first character of each word to uppercase.


Syntax:
string.title()

6. str.strip(): Removes leading and trailing whitespaces from the string.


Syntax:
string.strip()

7. str.replace(): Replaces a specified substring with another substring.


Syntax:
string.replace(old, new)

8. str.find(): Finds the index of the first occurrence of a substring.


Syntax:
string.find(substring)

9. str.split(): Splits the string into a list of substrings based on a delimiter.


Syntax:
string.split(delimiter)

10. str.join(): Joins elements of an iterable (like a list) into a single string.
Syntax:
'delimiter'.join(iterable)

Conclusion: Hence we have successfully Implement Built-in Set and String functions.
Experiment No. 7

Aim: To implement Functions (Built-In, User Defined, and Anonymous).

Theory:

1. Built-In Functions:
Python comes with a rich set of built-in functions that provide fundamental operations and
functionalities. Here's an overview of some of the commonly used built-in functions in Python:
● len(iterable): Returns the length (number of items) of an iterable object, such as a string, list,
tuple, etc.
● type(object): Returns the type of the object.
● print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False): Prints the specified objects to
the standard output (usually the console).
● input(prompt=''): Reads a line from the standard input (usually the console) and returns it as a
string.
● int(x, base=10), float(x), str(object): Convert a number or string to an integer, float, or string,
respectively.
● list(iterable), tuple(iterable), set(iterable): Creates a list, tuple, or set from the elements of an
iterable.
● max(iterable, *args, key=None), min(iterable, *args, key=None): Returns the maximum or
minimum element from an iterable (or among the arguments).
● sum(iterable, start=0): Returns the sum of all elements in an iterable, with an optional start
value.
● sorted(iterable, key=None, reverse=False): Returns a new sorted list from the elements of an
iterable.
● range(stop), range(start, stop, step): Generates a sequence of numbers within a specified
range.

2. User-Defined Functions:
User-defined functions in Python allow you to create your own reusable blocks of code. Here
are the key aspects of defining user-defined functions in Python without specific code examples:
Syntax: def function_name(parameters):Function body is indented
● Function Name: Descriptive and follows naming conventions.
● Parameters: Variables in parentheses, used within the function.
● Function Body: Contains code executed when the function is called.
● Return Statement: Return specifies the value to be returned.
● Calling a Function: Executed by using function_name(arguments).
● Default Values: Parameters can have default values.

3. Anonymous Functions:
Anonymous functions in Python are created using the lambda keyword. Here are the key
aspects of anonymous functions:
Lambda Function: Anonymous functions are defined using the lambda keyword, followed by
parameters and an expression.
Syntax: lambda parameters: expression.
● No Name:
● Lambda functions are anonymous because they don't have a name like regular functions
defined with def.
● Single Expression:
● Lambda functions are limited to a single expression, and the result of the expression is
implicitly returned.
● Used for Small Operations:
● Lambda functions are often used for small operations and as arguments to higher-order
functions like map(), filter(), and sorted().
● Conciseness:
● Lambda functions are concise and useful when a full function definition is unnecessary.
● No Statements:
● Lambda functions can only contain expressions, not statements.
● Immutable:
● Lambda functions create anonymous functions, and once defined, their behavior cannot be
changed.

Conclusion: Hence we have successfully implemented Built-In, User-Defined and Anonymous


functions.
Experiment No. 8

Aim: To implement Classes, object, Static method, constructors and Inner class.

Theory:
1. Classes and Objects:
● A class is a blueprint for creating objects. Objects are instances of classes.
● Classes encapsulate data (attributes) and behaviors (methods) related to a particular concept.
Syntax:
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def my_method(self):
# method code here

2. Constructors:
● A constructor (__init__ method) initializes the attributes of an object when it is created.
● It is called automatically when an object is instantiated.
Syntax:
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

3. Static Method:
● A static method belongs to the class rather than an instance of the class.
● It is defined using the @staticmethod decorator.
● Static methods do not have access to instance-specific data.
Syntax:
class MyClass:
@staticmethod
def my_static_method():
# static method code here

4. Inner Class:
● An inner class is a class defined within another class.
● It is used to logically group classes that are only used in one place.

Syntax:
class OuterClass:
def __init__(self):
# outer class constructor

class InnerClass:
def __init__(self):
# inner class constructor

Conclusion: Hence we have successfully implemented Classes, object, Static method, constructors
and Inner class.
Experiment No. 9
Aim: To implement different types of inheritance

Theory:

Inheritance in Python is a mechanism that allows a new class (subclass or derived class) to inherit
attributes and behaviors from an existing class (superclass or base class). This promotes code reuse,
extensibility, and the creation of a hierarchical structure among classes. The class that is inherited from is
known as the parent class, while the class that inherits is called the child class.

Types of inheritance in python are:

Single Inheritance: In single inheritance, a class can inherit attributes and behaviors from only one
parent class.

Multilevel Inheritance:
Multilevel inheritance involves a chain of inheritance where a class inherits from another class, and then
another class inherits from the derived class.
Syntax:
class BaseClass:
# Base class members

class DerivedClass1(BaseClass):
# Derived class 1 members

class DerivedClass2(DerivedClass1):
# Derived class 2 members

Hierarchical Inheritance: Hierarchical inheritance occurs when multiple classes inherit from a single
parent class.
Syntax:
class BaseClass:
# Base class members

class DerivedClass1(BaseClass):
# Derived class 1 members

class DerivedClass2(BaseClass):
# Derived class 2 members
Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance mentioned
above.

Syntax:
class BaseClass1:
# Base class 1 members

class BaseClass2:
# Base class 2 members

class DerivedClass1(BaseClass1):
# Derived class 1 members

class DerivedClass2(DerivedClass1, BaseClass2):


# Derived class 2 members

class DerivedClass3(BaseClass1):
# Derived class 3 members

class DerivedClass4(DerivedClass3, BaseClass2):


# Derived class 4 members

Cyclic Inheritance: Cyclic inheritance occurs when a class is derived from itself directly or indirectly.
Syntax:
class CyclicClass(CyclicClass): # Cyclic inheritance
# Class members

Conclusion: Hence we have successfully implemented Inheritance in python.


Experiment No. 10

Aim: To implement Polymorphism with Method Overloading and Overriding.

Theory:

Polymorphism allows objects of different types to be treated as objects of a common base type, providing
a unified interface for interacting with diverse classes.

Compile-Time Polymorphism (Method Overloading):


Method overloading allows a method to perform different actions based on the number or type of
parameters.
Syntax: class ClassName:
def method_name(self, param1, param2, optional_param=None):
# Method implementation

Runtime Polymorphism (Method Overriding):


Method overriding occurs when a subclass provides a specific implementation for a method already
defined in its superclass
Syntax:class SubClass(BaseClass):
def overridden_method(self):
# specific implementation

Conclusion: Hence we have successfully implemented Polymorphism with Method Overloading and
Overriding
Experiment No. 11

Aim: To implement Abstract class, Abstract method and Interfaces in Python.

Theory:

In Python, abstract classes and methods are implemented using the ABC (Abstract Base Class) module
from the abc package. Interfaces, in the strict sense of the term, are not explicitly defined in Python, but
you can achieve similar functionality using abstract classes.

1. Abstract Class:
An abstract class in Python is created using the ABC (Abstract Base Class) module from the abc
package. It may contain both abstract methods and regular methods.

Syntax:
from abc import ABC, abstractmethod
class AbstractClassExample(ABC):
@abstractmethod
def abstract_method(self):
pass
def regular_method(self):
print("This is a regular method.")

● The ABC class is imported from the abc module.


● @abstractmethod decorator is used to declare an abstract method.
● Regular methods can also be present in the abstract class.

2. Abstract Method:
An abstract method is a method declared in an abstract class without providing an implementation in the
abstract class. It serves as a blueprint for methods that must be implemented by concrete subclasses.
syntax:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass

● The @abstractmethod decorator is used to declare an abstract method.


● Concrete subclasses must provide a concrete implementation for the abstract method.
3. Interfaces in Python:
Interfaces in Python are not explicitly defined but can be achieved using abstract classes with abstract
methods. Classes that inherit from such abstract classes are expected to provide concrete
implementations for the abstract methods.

syntax:
from abc import ABC, abstractmethod
class Drawable(ABC):
@abstractmethod
def draw(self):
pass

● Drawable is an interface-like abstract class with an abstract method draw.


● Classes inheriting from Drawable must implement the draw method.

Conclusion: Hence we have successfully implemented python programs to implement Abstract class,
Abstract method and Interfaces in Python.
Experiment No. 12

Aim: To implement user- defined modules/ packages and import them in a program.

Theory:

User-defined Modules: A module is a Python file containing functions, variables, or classes that you can
import into other Python scripts using the import statement.
Syntax:
# Module creation: Create a file named my_module.py
# Define functions, variables, or classes in my_module.py
# Using the module in another Python file
import my_module
# Access functions, variables, or classes defined in my_module using my_module.function_name

User-defined Packages: Package is a directory containing multiple Python modules. To import specific
modules from the package, use the from package_name import module_name.
Syntax:
# Package creation: Create a directory named my_package
# Inside my_package, create multiple Python files (modules)
# Using the package in another Python file
from my_package import my_module
# Access functions, variables, or classes defined in my_module inside my_package using
my_module.function_name

Conclusion: Hence we have successfully implemented python programs to implement user- defined
modules/ packages and import them in a program.
Experiment No. 13

Aim: To implement multithreaded application in python

Theory:

Multithreading:

Multithreading is a concurrent execution model where multiple threads run in a single process, sharing the
same resources such as memory space, but each having its own execution flow.

Python's Global Interpreter Lock (GIL): One important thing to note when dealing with multithreading
in Python is the Global Interpreter Lock (GIL). The GIL is a mutex that protects access to Python objects,
preventing multiple threads from executing Python bytecodes at once.

The threading Module: Python provides the threading module for creating and working with threads. It
offers a convenient way to create, start, and manage threads.

Thread Safety: When multiple threads share data, it's crucial to ensure thread safety. This involves
preventing race conditions and ensuring that data is accessed and modified in a way that avoids conflicts.

Syntax:
def task1()
# Task logic for thread 1
pass
def task2():
# Task logic for thread 2
pass
# Create thread object
thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)

Conclusion: Hence we have successfully implemented a multithreaded application in python.


Experiment No. 14

Aim: To create a menu driven application which should cover all the built-in exceptions in python.
Theory:
1. exception BaseException: This is the base class for all built-in exceptions. It is not meant to be
directly inherited by user-defined classes.

Syntax:
try:
...
except SomeException:
tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)

2. exception Exception: This is the base class for all built-in non-system-exiting exceptions. All
user-defined exceptions should also be derived from this class.

3. exception ArithmeticError: This class is the base class for those built-in exceptions that are raised
for various arithmetic errors such as :
● OverflowError
● ZeroDivisionError
● FloatingPointError

4. exception BufferError: This exception is raised when buffer related operations cannot be
performed.

5. exception LookupError: This is the base class for those exceptions that are raised when a key or
index used on a mapping or sequence is invalid or not found.
The exceptions raised are :
● KeyError
● IndexError

6. exception AssertionError: An AssertionError is raised when an assert statement fails.

7. exception AttributeError: An AttributeError is raised when an attribute reference or assignment


fails such as when a non-existent attribute is referenced.

8. exception EOFError: An EOFError is raised when built-in functions like input() hits an end-of-file
condition (EOF) without reading any data. The file methods like readline() return an empty string when
they hit EOF.

9. exception FloatingPointError: A FloatingPointError is raised when a floating point operation fails.


This exception is always defined, but can only be raised when Python is configured with
the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.

10. exception GeneratorExit: This exception directly inherits from BaseException instead of
Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or
coroutine is closed.

11. exception ImportError: An ImportError is raised when the import statement is unable to load a
module or when the “from list” in from … import has a name that cannot be found.

Conclusion: Hence we have successfully implemented a python program to create a menu driven
application which should cover all the built-in exceptions in python.
Experiment No. 15

Aim: To implement File Handling operations in Python.

1. Writing to a File:

# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is a sample text.\n")
file.write("Python is awesome!\n")

Explanation:
● open("example.txt", "w"): Opens the file named "example.txt" in write mode.
● with ... as file: Utilizes the with statement to automatically close the file when the block is exited.
● file.write("..."): Writes the specified text to the file.

2. Reading from a File:

with open("example.txt", "r") as file:


content = file.read()
print(content)
Explanation:
● open("example.txt", "r"): Opens the file named "example.txt" in read mode.
● with ... as file: Ensures that the file is properly closed after reading.
● file.read(): Reads the entire content of the file into a string.

3. Appending to a File:

# Appending to a file
with open("example.txt", "a") as file:
file.write("Appending more text to the file.\n")

Explanation:
● open("example.txt", "a"): Opens the file named "example.txt" in append mode.
● with ... as file: Ensures proper closure of the file.
● file.write("..."): Appends the specified text to the end of the file.

4. Reading Lines from a File:

# Reading lines from a file


with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # Strip to remove newline characters

Explanation:
● open("example.txt", "r"): Opens the file named "example.txt" in read mode.
● with ... as file: Ensures proper closure of the file.
● file.readlines(): Reads all lines from the file and returns them as a list.
● for line in lines:: Iterates through the list of lines.
● line.strip(): Removes leading and trailing whitespaces, including newline characters.

5. Using with Statement for File Handling:

# Using with statement for automatic file closure


with open("example.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed outside the 'with' block

Explanation:
● The with statement is used to ensure that the file is properly closed after reading its content.
● It simplifies the code and reduces the risk of resource leaks.

6. Copying Contents from One File to Another:

# Copying contents from one file to another


with open("source.txt", "r") as source_file, open("destination.txt", "w") as dest_file:
dest_file.write(source_file.read())

Explanation:
● Two files (source.txt and destination.txt) are opened simultaneously using the with statement.
● The content of the source file is read and then written to the destination file.

7. Handling Exceptions during File Operations:

# Handling exceptions during file operations


try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print(f"An error occurred: {e}")

Explanation:

● try and except blocks are used to handle exceptions during file operations.
● In this example, the code attempts to open a file that doesn't exist, raising a FileNotFoundError.
● The specific exception is caught, and a corresponding message is printed. The generic Exception
class is used to catch other types of exceptions.

Conclusion: Hence we have successfully implemented python programs to implement File Handling
operations in Python.
Experiment No. 16

Aim: To implement GUI Application using Tkinter.

Theory:
GUI Application using Tkinter: Tkinter is a standard GUI (Graphical User Interface) toolkit in
Python. It allows you to create windows, buttons, text boxes, and other GUI elements.

Syntax:
import tkinter as tk

# Create a root window


root = tk.Tk()
root.title("My GUI Application") # Set the title of the window

# Create GUI elements (e.g., labels, buttons, etc.)


label = tk.Label(root, text="Hello, Tkinter!") # Create a label
button = tk.Button(root, text="Click Me!") # Create a button

# Add elements to the window using grid or pack layout manager


label.pack()
button.pack()

# Function to execute when the button is clicked


def on_button_click():
print("Button clicked!")

# Attach a function to the button click event


button.config(command=on_button_click)

# Start the GUI event loop


root.mainloop()

Tkinter Widgets
1. Button
The Button widget is used to display the buttons in your application.

2. Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your
application.

3.Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user can select
multiple options at a time.

4.Entry
The Entry widget is used to display a single-line text field for accepting values from a user.

5.Frame
The Frame widget is used as a container widget to organize other widgets.

6.Label
The Label widget is used to provide a single-line caption for other widgets. It can also contain images.

7.Listbox
The Listbox widget is used to provide a list of options to a user.

8.Menubutton
The Menubutton widget is used to display menus in your application.

9.Menu
The Menu widget is used to provide various commands to a user. These commands are contained inside
Menubutton.

10. Message
The Message widget is used to display multiline text fields for accepting values from a user.

11. Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The user can select only
one option at a time.

12. Scale
The Scale widget is used to provide a slider widget.

13. Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.

14. Text
The Text widget is used to display text in multiple lines.
15. Toplevel
The Toplevel widget is used to provide a separate window container.

16. Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from
a fixed number of values.

17. PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged horizontally or
vertically.

18. LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for
complex window layouts.

19. tkMessageBox
This module is used to display message boxes in your applications.

Geometry Management:
● The pack() Method − This geometry manager organizes widgets in blocks before placing them in
the parent widget.

● The grid() Method − This geometry manager organizes widgets in a table-like structure in the
parent widget.

● The place() Method − This geometry manager organizes widgets by placing them in a specific
position in the parent widget.

Conclusion: Hence we have successfully implemented GUI Application using Tkinter.


Experiment No. 17

Aim: To implement different types of plots using Numpy and Matplotlob.

Theory:
NumPy and Matplotlib: NumPy and Matplotlib are powerful libraries in Python used for numerical
computing and creating visualizations, respectively.

Syntax:

Line Plot:
import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100) # Create an array of values from 0 to 10
y = np.sin(x) # Compute sin(x)

# Plotting
plt.plot(x, y) # Create a line plot
plt.title('Sine Wave')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show() # Display the plot

Scatter Plot:
import matplotlib.pyplot as plt
import numpy as np

# Generate random data


x = np.random.rand(100) # Random values for x-axis
y = np.random.rand(100) # Random values for y-axis

# Plotting
plt.scatter(x, y) # Create a scatter plot
plt.title('Random Scatter Plot')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show() # Display the plot

Histogram:
import matplotlib.pyplot as plt
import numpy as np

# Generate random data


data = np.random.randn(1000) # Random data following a normal distribution

# Plotting
plt.hist(data, bins=30) # Create a histogram with 30 bins
plt.title('Histogram')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show() # Display the plot

Conclusion: Hence we have successfully implemented different types of plots using Numpy and
Matplotlob.

You might also like