Python Lab Programs
Python Lab Programs
Algorithm:
This code illustrates the implementation of two common built-in functions, sum() and max(), along
with tracing the data types of the values involved.
def my_sum(iterable):
"""
Return the sum of elements in the iterable.
"""
result = 0
for item in iterable:
result += item
return result
def my_max(iterable):
"""
Return the maximum element in the iterable.
"""
if not iterable:
raise ValueError("max() arg is an empty sequence")
max_value = iterable[0]
for item in iterable[1:]:
if item > max_value:
max_value = item
return max_value
Aim:
To implement conditional and iterative statements in Python to demonstrate basic
control flow mechanisms.
Algorithm:
1. Conditional Statements:
if statement: Check if a condition is true, and execute a block of code if
it is.
if-else statement: Check if a condition is true; if it is, execute one block
of code; otherwise, execute another block.
if-elif-else statement: Check multiple conditions sequentially, and
execute different blocks of code based on the first true condition
encountered.
2. Iterative Statements:
while loop: Repeat a block of code as long as a specified condition is
true.
for loop: Iterate over a sequence of elements (e.g., a list or a range of
numbers) and execute a block of code for each element.
# Conditional Statements
x = 10
y=5
# If statement
if x > y:
print("Aim: x is greater than y")
# If-else statement
if x < y:
print("Aim: x is less than y")
else:
print("Aim: x is not less than y")
# If-elif-else statement
if x < y:
print("Aim: x is less than y")
elif x == y:
print("Aim: x is equal to y")
else:
print("Aim: x is greater than y")
# Iterative Statements
# While loop
count = 0
while count < 5:
print("Aim: Count:", count)
count += 1
# For loop
for i in range(5):
print("Aim: i:", i)
# Nested loops
for i in range(3):
for j in range(2):
print("Aim: i:", i, "j:", j)
output:
Aim: x is greater than y
Aim: x is not less than y
Aim: x is greater than y
Aim: Count: 0
Aim: Count: 1
Aim: Count: 2
Aim: Count: 3
Aim: Count: 4
Aim: i: 0
Aim: i: 1
Aim: i: 2
Aim: i: 3
Aim: i: 4
Aim: i: 0 j: 0
Aim: i: 0 j: 1
Aim: i: 1 j: 0
Aim: i: 1 j: 1
Aim: i: 2 j: 0
Aim: i: 2 j: 1
EX.No.1.3
Aim:
Write a Python program to read and write from a CSV file by using built-in CSV module.
Algorithm
Step 1: A CSV (Comma Separated Values) format is one of the most simple and common ways to
store tabular data. To represent a CSV file, it must be saved with the .csv file extens
Step 3: Use the built-in open() function to work with CSV files in Python
Step 4: Before use the methods to the csv module, need to import the module first using import
command
Step 6: To write to a CSV file in Python, use the csv.writer() function.The csv.writer() function returns
a writer object that converts the user's data into a delimited string. This string can later be
open the people.CSV file using a text editor and store below data:
2, Jack, California
Program
Read from a CSV file
import csv
reader = csv.reader(file)
print(row)
Output
['SN', ' Name', ' City']
[]
writer = csv.writer(file)
Output
SN,Movie,Protagonist
print(ser)
Output:
B. numpy
import numpy as np
a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))
Output:
C. Chart
D. Graph
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
OUTPUT
Exp 2.1a) The floor of the white house consists of many squares and rectangle. Tom
wants to name single function of different perspective to calculate the area of
squares and rectangle. Help tom to achieve his objective by means of polymorphism.
Algorithm:
Program:
class Rectangle:
self.l = length
self.b = breadth
def area(self):
self.s = side
def area(self):
return self.s ** 2
squ = Square(9)
output
Exp 2.1b) Imagine a car. Its components such as steering, wheel, brake, accelerator
are all visible and can be accessed directly. Car engine was encapsulated so that we
can’t access it freely. Image these real time cirumstances develop a python program
to perform the concept of encapsulation.
Algorithm:
Program:
class car:
def __init__(self):
obj1 = car()
print(obj1.a)
output:
ERROR!
Program:
class llgm(ABC):
#abstract
classdef calculate_area(self):
#abstract methodpass
pass
class Square(llgm):
length = 5
def Area(self):
class Circle(llgm):
radius =4
def Area(self):
Exp 2.2b
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
"Abstarct Method"
pass
class SBI(Bank):
def interest(self):
s= SBI()
s.bank_info ()
s.interest()
Exp :2.3 Differentiate Method Overloading and Overriding.
ALGORITHM:
Method Overloading:
program:
class Human:
# Create instance
obj = Human()
output:
Hello
Hello cse
ALGORITHM
Method overriding:
Program:
class Employee:
def message(self):
print('This message is from Emp')
class Department(Employee):
def message(self):
print('This Department is inherited from Emp')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
output:
This message is from Emp
------------
This Department is inherited from Emp
EX.No.2.5
Aim:
Create a module called "math_operations.py" with a class called "Calculator." Import the
"Calculator" class into another script and use its methods to perform mathematical
operations..
Algorithm
Step 1: A module can contain functions, classes, and variables that can be used in other parts
of your program.
Step 3: Use the add() function to work with values assigned to the function in Python
Step 4: Before use the methods , need to import the module first using import
command
Program
# import math_operations.py
class calculator():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
obj=calculator(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output
1. Create a text file called "numbers.txt" and write the numbers from 1
to 10 in words, each on a separate line.
Ex.No:3.1
Aim: To create a text file called "numbers.txt" and write the numbers
from 1 to 10 in words, each on a separate line using python.
Algorithm:
Program:
# Open the file in write mode and write the numbers in words
Output:
Copy and paste this code into a Python file numbers_file.py and run
it.
It will generate a file named "numbers.txt" with each number from 1
to 10 written in words on separate lines.
Result:
Thus the given program was executed successfully.
Ex.No:3.2
2. Write a python program that Implement a custom iterator that
generates a sequence of Fibonacci numbers and print the first10
numbers.
AIM :
To write a program to Implement a custom iterator that generates a sequence
of Fibonacci numbers and print the first 10 Numbers
ALGORITHM: Fibonacci Iterator
1. Create a class named FibonacciIterator.
2. Initialize class attributes (limit, a, b, count) in the _init_ method.
3. Implement the _iter_ method to return the iterator object.
4. Implement the _next_ method to generate the next Fibonacci number.
- Update a and b, increment count.
- Check if count >= limit, raise StopIteration.
- Return the current Fibonacci number.
5. Instantiate FibonacciIterator with the desired limit.
6. Iterate over the Fibonacci sequence using a for loop.
- Print each generated Fibonacci number.
7. Run the program.
PROGRAM:
class FibonacciIterator:
def _init_(self, limit):
self.limit = limit
self.a, self.b = 0, 1
self.count = 0
def _iter_(self):
return self
def _next_(self):
if self.count>= self.limit:
raise StopIteration
result = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return result
# Example usage:
if _name_ == "_main_":
fibonacci_sequence = FibonacciIterator(10)
OUTPUT:
Here's the output for the provided Python program that implements a
custom iterator for generating the first 10 Fibonacci numbers:
0
1
1
2
3
5
8
13
21
34
This output corresponds to the first 10 Fibonacci numbers in the
sequence. The iterator starts with 0 and 1 and generates subsequent
numbers by adding the previous two numbers in the sequence.
Result:
Thus the given program was executed successfully.
Ex.No:3.3
AIM:
Create a try except block to catch a ‘File not Found’ Error and print message
when file is not found
ALGORITHM
Step 1: Start program
Step 2: Try opening the file using Open command
Step 3: If file not found print ‘file not found’
Step 4: End Program
Program:
try:
file1 =open("Myfolder/abc.txt")
except:
print("file not found")
Output
file not found
Result:
Thus the given program was executed successfully.
Ex.No:3.4
Write a python program that HANDLES A Zero Division Error and
prints a custom error message to the console.
AIM :
To write a python program that HANDLES A Zero Division Error and prints
a custom error message to the console
ALGORITHM:
1. Check if the divisor is zero: Before performing division, the program
checks if the divisor is zero.
2. If divisor is zero:
If the divisor is zero, raise an exception (often a ZeroDivisionError
in many programming languages).
The program may terminate or proceed to handle the exception based
on the context.
3. If divisor is not zero:
Perform the division operation as usual.
Return the result or proceed with further computations depending on
the program's logic.
4. Handle exceptions (optional):
In many programming languages, developers can choose to handle the
ZeroDivisionError exception explicitly using try-except blocks.
Handling the exception allows the program to gracefully respond to
the error condition, potentially avoiding crashes or providing
meaningful feedback to the user.
PROGRAM:
try:
numerator = 10
denominator = 0
# Check if denominator is zero
if denominator == 0:
raise ZeroDivisionError("Division by zero!")
# Perform division
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError as e:
print("Error:", e)
OUTPUT:
ERROR!
Error: Division by zero!
Result:
Thus the given program was executed successfully.
Ex.No:3.5
Program:
# greetings.py
defHello():
print('Hello, World! ')
# main.py
import greetings
greetings.Hello()
# Output:
# 'Hello, World!'
Result:
Thus the given program was executed successfully.
Ex.No:3.6
Install the numpy package using PIP, import the package and create a
numpy array with random values
Aim: To create a numpy array with random values in python
Program:
import numpy as np
# Define a 1D array
my_array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]],
dtype=np.int64)
# Define a 2D array
my_2d_array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]],
dtype=np.int64)
# Define a 3D array
my_3d_array = np.array([[[1, 2, 3, 4],
[5, 6, 7, 8]],
[[1, 2, 3, 4],
[9, 10, 11, 12]]],
dtype=np.int64)
# Print the 1D array
print("Printing my_array:")
print(my_array)
# Print the 2D array
print("Printing my_2d_array:")
print(my_2d_array)
# Print the 3D array
print("Printing my_3d_array:")
print(my_3d_array)
Result:Thus the given program was executed successfully.
Ex.No. 4.1
Design a gui form with vertical box layout that includes labels and entry fields for user registration in
python.
Python's tkinter to make a simple registration form. An ordinary Python library is Tkinter. The
quickest and simplest approach to create an object-oriented GUI application is with Python
and the tkinter package.
Frame : serves as a holding area for other widgets and serves as a container.
Text : It enables us to display and alter text in a variety of styles and offers a
Label : Used to display text and images, but we are unable to interact with it.
Button : Often used add buttons and we may add functions and methods to it.
container.
Listbox : It just has text elements, all of which are the same colour and font.
Scale : This widget offers graphical slider items that let us choose different scale
values.
Listbox : It just has text elements, all of which are the same colour and font.
Algorithm:
Step 1 : The first step is to import the tkinter module
(using either tkinter import * or just import tkinter).
Step 2 : The primary window of the GUI programme was created.
Step 3 : Include one or more widgets in the GUI programme (controls such as
buttons, labels, and text boxes, etc.).
Step 4 : Enter the primary events to react to each event that the user has triggered.
Coding
from tkinter import *
base = Tk()
base.geometry("500x500")
base.title("registration form")
output:
Result :
To design a GUI form with vertical box layout that includes labels and entry fields for user
registration in python was competed successfully.
Aim:
To create a GUI window with a grid layout that performs Tic-tac-toe game(3x3
board game).
Algorithm:
• Import tkinter module and message box
• Create a GUI window using tk() as the root window with title ‘Tic-Tac-Toe’
• Bind the button command to the function ‘clicked’ with its position as
arguments
• Attach button to root window using ‘grid’ layout with row and column
values
• Check if any row has the same symbol, display win status and
stop_game = True
• Check if any column has the same symbol, if yes display win status and
stop_game = True
• Check if any diagonal has the same symbol, display win status and
stop_game = True
• Check if all the 9 positions are filled: display tie and stop_game = True
Program:
stop_game = False
def clicked(r,c):
global Player
#X's turn
b[r][c].configure(text = "X")
Player='O'
#o's turn
b[r][c].configure(text = 'O')
Player = "X"
check_if_win()
if stop_game == True:
root.destroy()
def check_if_win():
global stop_game
for i in range(3):
#Horizontal match
stop_game = True
break
#Vertical Match
stop_game = True
break
#Left diagonal
stop_game = True
break
#Right diagonal
stop_game = True
break
#Tie case
elif b[0][0]['text'] and b[0][1]['text'] and b[0][2]['text'] and b[1][0]['text'] and
b[1][1]['text'] and b[1][2]['text'] and b[2][0]['text'] and b[2][1]['text'] and
b[2][2]['text'] != '':
stop_game = True
break
# Design window
root = Tk()
root.resizable(0,0)
b = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(3):
for j in range(3):
b[i][j].grid(row = i, column = j)
mainloop()
Output:
Result:
The program to create GUI board 3x3 board game with buttons was
successfully executed for Tic-tac-toe game
Ex.No:2.3.Create a canvas in your GUI program and draw simple shapes such
as rectangles, circles, and lines.
AIM :
To write a python program to implement GUI program and draw simple shapes
such as rectangles, circles, and lines.
ALGORITHM:
In this program we do some drawing. Drawing in Tkinter is done on the Canvas
widget. Canvas is a high-level facility for doing graphics in Tkinter.
It can be used to create charts, custom widgets, or create games.
Import the module tkinter and it’s canva class to create the required shapes
We are using a class to show the working of functions that helps to creates
different shapes.
Class parameters –
Source Code
# Imports each and every method and class
# of module tkinter and tkinter.ttk
from tkinter import *
from tkinter.ttk import *
class Shape:
def __init__(self, master = None):
self.master = master
# Calls create method of class Shape
self.create()
def create(self):
# Creates a object of class canvas
# with the help of this we can create different shapes
self.canvas = Canvas(self.master)
# Creates a circle of diameter 80
self.canvas.create_oval(10, 10, 80, 80,
outline = "black", fill = "white",
width = 2)
# Creates an ellipse with horizontal diameter
# of 210 and vertical diameter of 80
self.canvas.create_oval(110, 10, 210, 80,
outline = "red", fill = "green",
width = 2)
# Creates a rectangle of 50x60 (heightxwidth)
self.canvas.create_rectangle(230, 10,320, 60,outline = "black", fill =
"blue",width = 2)
# Creates an line
self.canvas.create_line(30, 200, 90, 100,
fill = "red", width = 2)
# Pack the canvas to the main window and make it expandable
self.canvas.pack(fill = BOTH, expand = 1)
if __name__ == "__main__":
# object of class Tk, responsible for creating
# a tkinter toplevel window
master = Tk()
shape = Shape(master)
# Sets the title to Shapes
master.title("Shapes")
# Sets the geometry and position
# of window on the screen
master.geometry("330x220 + 300 + 300")
# Infinite loop breaks only by interrupt
mainloop()
OUTPUT:
Exp.4.4 Create a GUI form program that includes various widgets and implement
event handling Concepts also add Create a drop-down menu that allows users to
select different font styles for text display.
Aim:
To create a GUI form program that includes various widgets and implement
event handling Concepts also add Create a drop-down menu that allows users to
select different font styles for text display.
Algorithm:
Step 1: Start by importing the Tk class from the tkinter module. This class is used to
create the main application window.
Step 2: A function named clicked is defined. This function will be called when the
"Submit" button is clicked. It retrieves the text entered in the Entry widgets for name,
department, and year, concatenates them with appropriate labels, and sets the
resulting text to the display Label widget. Additionally, it changes the font of the
display based on the option selected from the dropdown menu.
Step 4: Define Variables: Two variables Name and choosen are defined. These
variables will be associated with StringVar and StringVar objects respectively.
1. https://www.mongodb.com/try/download/community
2.
Click download, then the mongodb has been downloaded.
7.
8.
9.Open MongoCompass
10.Click Connect
11.Open IDLE
Coding:
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
print(client)
alldb=client.list_database_names()
print(alldb)
O/p:
Ex.No:5.2.Use a cursor to iterate over the records in a collection/table and
print specific fields/attributes
Algorithm:
1.Import pymongo
2.Connect with Mongocompas using MongoClient command
3.Create a ‘Employee’ data base
4.Create a collection ‘Information’
5.Create a document rec with
attributes{EMPNO,ENAME,JOB,HIREDATE,SAL,DEPTNO}
6.Finally insert the document into the collection using Insert_one or
insert_many command.
7.Open the Mongodb .The created collection will be displayed.
Program:
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
mydb=client['Employee']
information=mydb.table
rec={
"EMPNO" : 7934,
"ENAME" : "AAAAA",
"JOB" : "CLERK",
"HIREDATE" : "1.08.2018",
"SAL" : 35000,
"DEPTNO" : 10
doc=information.insert_one(rec)
print(doc)
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
mydb=client['Employee']
information=mydb.table
rec=[{
"EMPNO" : 7934,
"ENAME" : "AAAAA",
"JOB" : "CLERK",
"HIREDATE" : "1.08.2018",
"SAL" : 35000,
"DEPTNO" : 10
},
"EMPNO" : 7935,
"ENAME" : "BBBB",
"JOB" : "CODER",
"HIREDATE" : "1.08.2019",
"SAL" : 55000,
"DEPTNO" : 5
},
"EMPNO" : 7936,
"ENAME" : "CCCC",
"JOB" : "MANAGER",
"HIREDATE" : "1.08.2008",
"SAL" : 100000,
"DEPTNO" : 1 }
doc=information.insert_many(rec)
print(doc)
o/p:
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
mydb=client['Employee']
information=mydb.table
print(read)
o/p:
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
mydb=client['Employee']
information=mydb.table
dis=information.find()
print(record)
O/P:
Exp:5.3 Implement error handling for specific scenarios, such as duplicate key
violation or record not found, in the NoSQL database.
Program:
from pymongo import MongoClient
try:
client=MongoClient('mongodb://localhost:27017')
db = client['Employee']
collection = db['mm']
except CollectionInvalid as e: