Lab Manual of Python Fh25.Docx
Lab Manual of Python Fh25.Docx
PYTHON LAB
Lab Code: ITL404
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.
● 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.
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 Requirements:
Processor or higher
2. Minimum 2 GB RAM
Software Requirements:
3. Notepad ++
5. Mysql.
DETAILED SYLLABUS:
LO
Sr. No. Detailed Content Hours
Mapping
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
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:
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:
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:
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
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)
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
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()
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)
Conclusion: Hence we have successfully implemented Different Lists and List operations.
Experiment No. 5
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.
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)
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')
Conclusion: Hence we have successfully implemented Tuple Operations using Built-in function.
Experiment No. 6
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, ...)
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
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.
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.
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 DerivedClass3(BaseClass1):
# Derived class 3 members
Cyclic Inheritance: Cyclic inheritance occurs when a class is derived from itself directly or indirectly.
Syntax:
class CyclicClass(CyclicClass): # Cyclic inheritance
# Class members
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.
Conclusion: Hence we have successfully implemented Polymorphism with Method Overloading and
Overriding
Experiment No. 11
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.")
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
syntax:
from abc import ABC, abstractmethod
class Drawable(ABC):
@abstractmethod
def draw(self):
pass
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
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)
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
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.
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
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.
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.
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.
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.
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.
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
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
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.
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
# 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
# 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.