Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Python Lab Programs

Uploaded by

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

Python Lab Programs

Uploaded by

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

Experiment 1.

1: Implement built-in functions and trace the type of data items


Aim: The aim of this code is to implement simplified versions of the sum() and max() functions
and trace the type of data items passed to them.

Algorithm:

1. Define a function my_sum(iterable) to calculate the sum of elements in the iterable.


2. Initialize a variable result to store the sum.
3. Iterate through each item in the iterable and add it to the result.
4. Return the final value of result.
5. Define a function my_max(iterable) to find the maximum element in the iterable.
6. Check if the iterable is empty. If it is, raise a ValueError.
7. Initialize a variable max_value with the first element of the iterable.
8. Iterate through the remaining elements of the iterable and update max_value if a
larger element is found.
9. Return the final value of max_value.
10. Test both functions with a list of numbers.
11. Use the type() function to trace the data types of the list, the sum, and the maximum
value.

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

# Test the functions


my_list = [1, 5, 3, 9, 2]
print("Sum of my_list:", my_sum(my_list))
print("Max of my_list:", my_max(my_list))

# Tracing data types


print("Type of my_list:", type(my_list))
print("Type of sum of my_list:", type(my_sum(my_list)))
print("Type of max of my_list:", type(my_max(my_list)))
output:
Sum of my_list: 20
Max of my_list: 9
Type of my_list: <class 'list'>
Type of sum of my_list: <class 'int'>
Type of max of my_list: <class 'int'>
Experiment 1.2: Implement concepts of Conditional and Iterative
Statements.

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.

# Aim: Demonstrate conditional and iterative statements in Python

# 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 2: CSV file are separated by commas.

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 5: To read a CSV file in Python, use the csv.reader() function.

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

used to write into CSV files using the writerow() function.

open the people.CSV file using a text editor and store below data:

SN, Name, City

1, Michael, New Jersey

2, Jack, California

Program
Read from a CSV file

import csv

with open('people.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:

print(row)

Output
['SN', ' Name', ' City']

['1', ' Michael', ' New Jersey']


['2', ' Jack', ' California']

[]

Write to a CSV file


import csv

with open('protagonist.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["SN", "Movie", "Protagonist"])

writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])

writer.writerow([2, "Harry Potter", "Harry Potter"])

Output
SN,Movie,Protagonist

1,Lord of the Rings,Frodo Baggins

2,Harry Potter,Harry Potter


Ex.No.1.4
Aim:
Write a Python program to Perform data analysis and visualization on a given dataset
using Python libraries like pandas numpy, matplotlib and display charts, graphs, and
plots.
A. Panda
import pandas as pd
# a simple dictionary
dict = {'raju': 10,
'babu': 20,
'somu': 30}
# create series from dictionary
ser = pd.Series(dict)

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))

# specify sort algorithm


print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))

# Example to show sorting of structured array


# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n",


np.sort(arr, order = ['grad_year', 'cgpa']))

Output:

C. Chart

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)


plt.legend(title = "Four Fruits:")
plt.show()
Output

D. Graph

import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('Python graph')

# function to show the plot


plt.show()

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.

Aim: Program to illustrate polymorphism

Algorithm:

Step1: create a class named rectangle

Step2: Input length and breadth

Step3: create a function area

Step4: calculate area =length x breadth

Step5: return the value area

Step6: create a class square

Step7: Input side value

Step8: create a function area

Step9: calculate area =side x side

Step10: return the value area

Program:

class Rectangle:

def __init__(self, length, breadth):

self.l = length

self.b = breadth

def area(self):

return self.l * self.b


class Square:

def __init__(self, side):

self.s = side

def area(self):

return self.s ** 2

rec = Rectangle(5, 20)

squ = Square(9)

print("Area of rectangle is: ", rec.area())

print("Area of square is: ", squ.area())

output

Area of rectangle is: 100

Area of square is: 81

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:

Step 1: create class car

Step 2: declare a variable a

Step 3: declare a variable double underscore c

Step 4: assign a= steering

Step 5: assign c=engine

Step 6: create a object ob1 for class car


Step 7: access the variable a

Step 8: access the variable double underscore c

Program:

# program to implement encapsulation

class car:

def __init__(self):

self.a = "steering-accessing normal variable"

self.__c = "engine" #double underscore before the variable makes it as private

obj1 = car()

print(obj1.a)

print("try to access private variable but is shows............error as")

print(obj1.__c) # try to access private variable

output:

steering-accessing normal variable

try to access private variable but is shows............error as

Traceback (most recent call last):

File "<string>", line 10, in <module>

ERROR!

AttributeError: 'car' object has no attribute '__c'


Exp 2.2a) Implement Data Abstraction and Inheritance.

Aim: Program to illustrate Data Abstraction and Inheritance

Program:

#from abc import ABC

class llgm(ABC):

#abstract

classdef calculate_area(self):

#abstract methodpass

pass

class Square(llgm):

length = 5

def Area(self):

return self.length * self.length

class Circle(llgm):

radius =4

def Area(self):

return 3.14 * self.radius * self.radius

sq = Square() #object created for the class ‘Square’

cir = Circle() #object created for the class ‘Circle’

print("Area of a Square:", sq.Area()) #call to ‘calculate_area’ method


defined inside the class ‘Square’
print("Area of a circle:", cir.Area())

Exp 2.2b

#from abc import ABC, abstractmethod

#Abstract Class

class Bank(ABC):

def bank_info(self):

print("Welcome to bank")

@abstractmethod

def interest(self):

"Abstarct Method"

pass

#Sub class/ child class of abstract class

class SBI(Bank):

def interest(self):

"Implementation of abstract method"

print("In sbi bank 5 rupees interest")

s= SBI()

s.bank_info ()

s.interest()
Exp :2.3 Differentiate Method Overloading and Overriding.

AIM: To Differentiate Method Overloading and Overriding.

ALGORITHM:
Method Overloading:

1) We create a class with one method sayHello().


2) The first parameter of this method is set to None.
3) This gives us the option to call it with or without a parameter.
4) An object is created based on the class
5) we call its method using zero and one parameter.
6) To clarify method overloading, we can now call the method sayHello() in two ways:
i)obj.sayHello()
ii)obj.sayHello('cse')

program:

class Human:

def sayHello(self, name=None):

if name is not None:


print('Hello ' + name)
else:
print('Hello ')

# Create instance
obj = Human()

# Call the method


obj.sayHello()

# Call the method with a parameter


obj.sayHello('cse')

output:
Hello
Hello cse
ALGORITHM
Method overriding:

1) created an employee class


2) which contains a message function that prints a message.
3) Next, we created a department that inherits from the Employee class.
4) Within this, we created a function with the same name message with a different print message.
5) Here, we are just overriding the message. Next, we created an Object for Employee and Department
class and calling that message function.
6) The emp object is printing a string from the Employee message function. Whereas dept.message() is a
printing test from Department.

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 2: In , the module “math_operations.py” contains a function called “add”


,”Sub”,”multiply”,divide…etc and a class called “calc”. These can be imported and used in
other Python scripts with the class calc().

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

Step 5: Run the code and execute the output

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

#from math_operations.py import add, mul, div , sub

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

b=int(input("Enter second number: "))

obj=calculator(a,b)

choice=1

while choice!=0:

print("0. Exit")

print("1. Add")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

choice=int(input("Enter choice: "))

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

Enter first number: 12


Enter second number: 12
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 1
Result: 24
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 2
Result: 0
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 3
Result: 144
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 4
Result: 1.0
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 0
Exiting!
Unit – 3 Files and Exceptions Handling, Modules, Packages

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:

1. Open a new text file named "numbers.txt" in write mode.


2. Create a list of number words from 1 to 10.
3. Iterate through the list and write each word to the file followed
by a newline character.
4. Close the file.

Program:

numbers_in_words = ["One", "Two", "Three", "Four", "Five", "Six",


"Seven", "Eight", "Nine", "Ten"]

# Open the file in write mode and write the numbers in words

with open("numbers.txt", "w") as file:


for number, word in enumerate(numbers_in_words, start=1):
file.write(f"{word}\n")

print("File 'numbers.txt' has been created with numbers written 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)

for number in fibonacci_sequence:


print(number)

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

5. Create a module called "greetings.py" with a function called "hello"


that prints "Hello, World!" Import the module into another script and
use the "hello" function.

Aim- To write a python program to create a module called “greeting.py”


with a function called “hello” the print “Hello, World!”.
Algorithm:
Step 1- Create a Module Named “greetings.py”.
Step 2- Create a Function Named “hello”.
Step 3-Import that module in another program by using the “hello”
function.
Step 4- Print "Hello, World!".

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.

Some of the common widgets used in Tkinter are :

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

prepared text display.

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.

Entry : One-line string text can be entered into this widget.

Labelframe : For intricate window layouts, this widget serves as a separator or

container.

Listbox : It just has text elements, all of which are the same colour and font.

Scrollbar: This gives a sliding controller.

Canvas : Custom widgets can be implemented using the canvas widget.

Scale : This widget offers graphical slider items that let us choose different scale

values.

Radiobutton : Use a radio button to carry out one of several choices.

Checkbox : Use a checkbox to implement on-off choices.

Listbox : It just has text elements, all of which are the same colour and font.

How to start making a simple registration form using Tkinter :

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.
Aim:
Design a gui form with vertical box layout that includes labels and entry
fields for user registration in python.

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")

lb1= Label(base, text="Enter Name", width=10, font=("arial",12))


lb1.place(x=20, y=120)
en1= Entry(base)
en1.place(x=200, y=120)

lb3= Label(base, text="Enter Email", width=10, font=("arial",12))


lb3.place(x=19, y=160)
en3= Entry(base)
en3.place(x=200, y=160)

lb4= Label(base, text="Contact Number", width=13,font=("arial",12))


lb4.place(x=19, y=200)
en4= Entry(base)
en4.place(x=200, y=200)

lb5= Label(base, text="Select Gender", width=15, font=("arial",12))


lb5.place(x=5, y=240)
vars = IntVar()
Radiobutton(base, text="Male", padx=5,variable=vars, value=1).place(x=180,
y=240)
Radiobutton(base, text="Female", padx =10,variable=vars,
value=2).place(x=240,y=240)
Radiobutton(base, text="others", padx=15, variable=vars,
value=3).place(x=310,y=240)

list_of_cntry = ("United States", "India", "Nepal", "Germany")


cv = StringVar()
drplist= OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set("United States")
lb2= Label(base, text="Select Country", width=13,font=("arial",12))
lb2.place(x=14,y=280)
drplist.place(x=200, y=275)

lb6= Label(base, text="Enter Password", width=13,font=("arial",12))


lb6.place(x=19, y=320)
en6= Entry(base, show='*')
en6.place(x=200, y=320)

lb7= Label(base, text="Re-Enter Password", width=15,font=("arial",12))


lb7.place(x=21, y=360)
en7 =Entry(base, show='*')
en7.place(x=200, y=360)

Button(base, text="Register", width=10).place(x=200,y=400)


base.mainloop()

from tkinter import *


base = Tk()
base.geometry("500x500")
base.title("registration form")

lb1= Label(base, text="Enter Name", width=10, font=("arial",12))


lb1.place(x=20, y=120)
en1= Entry(base)
en1.place(x=200, y=120)

lb3= Label(base, text="Enter Email", width=10, font=("arial",12))


lb3.place(x=19, y=160)
en3= Entry(base)
en3.place(x=200, y=160)
lb4= Label(base, text="Contact Number", width=13,font=("arial",12))
lb4.place(x=19, y=200)
en4= Entry(base)
en4.place(x=200, y=200)

lb5= Label(base, text="Select Gender", width=15, font=("arial",12))


lb5.place(x=5, y=240)
vars = IntVar()
Radiobutton(base, text="Male", padx=5,variable=vars, value=1).place(x=180,
y=240)
Radiobutton(base, text="Female", padx =10,variable=vars,
value=2).place(x=240,y=240)
Radiobutton(base, text="others", padx=15, variable=vars,
value=3).place(x=310,y=240)

list_of_cntry = ("United States", "India", "Nepal", "Germany")


cv = StringVar()
drplist= OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set("United States")
lb2= Label(base, text="Select Country", width=13,font=("arial",12))
lb2.place(x=14,y=280)
drplist.place(x=200, y=275)

lb6= Label(base, text="Enter Password", width=13,font=("arial",12))


lb6.place(x=19, y=320)
en6= Entry(base, show='*')
en6.place(x=200, y=320)

lb7= Label(base, text="Re-Enter Password", width=15,font=("arial",12))


lb7.place(x=21, y=360)
en7 =Entry(base, show='*')
en7.place(x=200, y=360)

Button(base, text="Register", width=10).place(x=200,y=400)


base.mainloop()

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.

Ex 4.2: GUI window with a grid layout and buttons

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 global variables Player and stop_game initialized to False

• Create a GUI window using tk() as the root window with title ‘Tic-Tac-Toe’

• Create a 2-dimensional array for storing the 9 positions as buttons

• Create buttons for each positions

• Assign height, width, font for the button

• 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

• Create the function ‘clicked’ to perform the playing layout

• Check current player

• Add the player’s symbol to the given position

• Check if there is a win or tie condition

• Destroy the window when stop_game is True, otherwise continue


playing

• Create the function ‘check_if_win to check if game is over

• 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:

from tkinter import *

from tkinter import messagebox

Player = 'X'#First player

stop_game = False

def clicked(r,c):

global Player

#X's turn

if Player == "X" and b[r][c]['text'] == '' and stop_game == False:

b[r][c].configure(text = "X")

Player='O'

#o's turn

if Player == 'O' and b[r][c]['text'] == '' and stop_game == False:

b[r][c].configure(text = 'O')

Player = "X"

#Check if game is over

check_if_win()

if stop_game == True:

root.destroy()

def check_if_win():

global stop_game

for i in range(3):
#Horizontal match

if b[i][0]['text'] == b[i][1]['text'] == b[i][2]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner", b[i][0]['text'] + " Won")

break

#Vertical Match

elif b[0][i]['text'] == b[1][i]['text'] == b[2][i]['text'] != '':

stop_game = True

winner = messagebox.showinfo("Winner", b[0][i]['text']+ " Won!")

break

#Left diagonal

elif b[0][0]['text'] == b[1][1]['text'] == b[2][2]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner", b[0][0]['text']+ " Won!")

break

#Right diagonal

elif b[0][2]['text'] == b[1][1]['text'] == b[2][0]['text'] !='':

stop_game = True

winner = messagebox.showinfo("Winner" , b[0][2]['text']+ " Won!")

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

winner = messagebox.showinfo("tie", "Tie")

break

# Design window

root = Tk()

root.title("Tic Tac Toe")

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] = Button(height = 2, width = 4, font = ("Helvetica","20"),

command = lambda r = i, c = j : clicked(r,c))

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

Canvas Methods for shapes:


Canvas.create_oval(x1, y1, x2, y2, options = …): It is used to create a oval,
pieslice and chord.
Canvas.create_rectangle(x1, y1, x2, y2, options = …): It is used to create
rectangle and square.
Canvas.create_line(x1, y1, x2, y2, options = …) This is used to create an line.
Canvas.create_polygon(coordinates, options = …) THis is used to create any
valid shapes.

We are using a class to show the working of functions that helps to creates
different shapes.
Class parameters –

Data members used: master, canvas


Member functions used: create() method
Widgets used: Canvas
Tkinter method used:
Canvas.create_oval()
Canvas.create_rectangle()
Canvas.create_line ()
pack()
title()
geometry()

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:

Result: Thus the program is executed successfully.

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 3: Create Main Window: An instance of the Tk class is created, representing


the main application window. The title of the window is set to "GUI Form" and its
size is defined as 200x200 pixels.

Step 4: Define Variables: Two variables Name and choosen are defined. These
variables will be associated with StringVar and StringVar objects respectively.

Step 5: Create Widgets:


Labels: Labels for "DETAILS", "Name:", "Year:", "Dept:", and "Font" are
created and placed using the grid() method to organize them in rows and columns.
Entry Widgets: Entry widgets for entering the name, year, and department are
created and placed adjacent to their respective labels using the grid() method.
OptionMenu Widget: An OptionMenu widget is created to select the font. The
font options are provided as a dropdown menu. The default option is set to "select".
Button Widget: A button labeled "Submit" is created. When clicked, it will
call the clicked() function.
Display Label Widget: A Label widget named display is created to display the
entered details. Initially, it displays placeholders for Name, Department, and Year.
Step 6: Mainloop: The mainloop() method is called on the Tk instance to start the
event loop. This keeps the application running and responsive to user interactions
un1til the window is closed.
Program:
from tkinter import *
def clicked():
display.config(text = "Name:" + name_e.get() + "\nDept:" + dept_e.get() +
"\nYear:" + year_e.get())
display.config(font = choosen.get())
root = Tk()
root.title("GUI Form")
root.geometry("200x200")
Name = StringVar()
details = Label(root, text = "DETAILS")
details.grid(row = 0, column = 0, columnspan = 2)
name = Label(root, text = "Name:")
name.grid(row = 1, column = 0)
name_e = Entry(root)
name_e.grid(row = 1, column = 1)
year = Label(root, text = "Year:")
year.grid(row = 2, column = 0)
year_e = Entry(root)
year_e.grid(row = 2, column = 1)
dept = Label(root, text = "Dept:")
dept.grid(row = 3, column = 0)
dept_e = Entry(root)
dept_e.grid(row = 3, column = 1)
font = Label(root, text = "Font")
font.grid(row = 4, column = 0)
options = ['Arial', 'Helvetica', 'Times']
choosen = StringVar()
choosen.set('select')
drop = OptionMenu(root , choosen , *options)
drop.grid(row = 4, column = 1)
submit = Button(root, text = "Submit", command = clicked)
submit.grid(row = 5, column = 0, columnspan = 2)
display = Label(root, text = 'Name:\nDept:\nYear:')
display.grid(row = 8, column = 0, columnspan = 2)
mainloop()
OUTPUT:
Result: Thus the program is executed successfully.
Ex.No : 5.1 Connect to the NoSQL database using a Python connector module,
such as "pymongo" for MongoDB or "cassandra-driver" for Cassandra.

1. https://www.mongodb.com/try/download/community

Click The Select Package

2.
Click download, then the mongodb has been downloaded.

3.Open the exe file from download ,then click next.

4.In next window select the complete,then click next.


5.Mongodb will be downloaded in the PC.

6.Open command prompt

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)

12.Run the program

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)

//Create a More one collection

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:

//find the collection

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']
information=mydb.table

read = information.find_one({"ENAME": "CCCC"})

print(read)

o/p:

Find all the collection

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']

information=mydb.table

#print the collection in the database

dis=information.find()

for record in dis:

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

from pymongo.errors import CollectionInvalid

try:

client=MongoClient('mongodb://localhost:27017')

db = client['Employee']

collection = db['mm']

except CollectionInvalid as e:

print(f"Collection not found error: {e}")

You might also like