Lab Manual PYTHON
Lab Manual PYTHON
LAB MANUAL
LABTASKS
TASK
NAME OF TASK CO
NO
1 Running Python Script and various expressions in an interactive interpreter CO1
2 Implement conditional, control and looping statements. CO1
Importing and Creating Python modules and packages in python
3 CO1
programming
Use various data types, List, Tuples, Sets and Dictionary in python
4 CO1
programming
Implement various Searching and Sorting Operations in python
5 CO2
programming
6 Implement various text/CSV file operations. CO2
7 Utilizing ‘Functions’ concepts in Python Programming. CO2
TImplement Multi-Threading concepts using threading module in Python
8 CO3
Programming.
9 Implement Exceptions and Exceptional handling in Python CO3
10 Use Matplotlib module for plotting in python. CO4
11 Use pandas Library to process Data Frames in Python CO5
12 Use Tkinter module for UI design CO5
13 Simulate Gaming concepts using pygame CO5
14 Case study: Build any one classical data structure using python CO5
15 Case study: Booking Management system using Tkinter CO5
16 Case study: Simple hotel management system using Tkinter CO5
17 Case study: 8 Polls game design using Pygame CO5
18 Case study: Angry bird design using pygame CO5
Task 1: Design and develop programs for evaluating the equations: Implement it
Aim:
To design and develop a program for evaluating the equation
Algorithm:
Step1: Start.
Step2: Read the values of u,a,t.
Step3:Compute v = u + (a*t) and display the result of velocity.
Step4: Compute s = (u*t) + (0.5*a*(t*t)) and display the result of displacement.
Step5: Compute l = ((v*v) - (u*u)).
Step 6: Compute p = 2 * a*s
Step 7: Check l is equal to p.
Step 8: Stop.
Program:
u=int(input("Enter the value of u:"))
a=int(input("Enter the value of a:”))
t=int(input("Enter the value of t:"))
v=u+(a*t)
s=(u*t)+(0.5*a*(t*t))
l=(v*v)-(u*u)
p=2*a*s
if(p==l):
print("Equation evaluated")
else:
print("Equation not evaluated")
Output:
Enter the value of u: 5
Enter the value of a: 3
Enter the value of t: 1
Equation evaluated
Result:
Thus the python program is performed to evaluate the equation in an interactive interpreter.
Task 2: Implement conditional, control and looping statements.
Aim:
To develop a Python program to implement theconditional, control and looping statements using the Rock-
Paper-Scissor game.
Algorithm:
Step 1: Start the program.
Step 2: Repeat step 3 to 8 until the condition i<n
Step 3:Take the input from user p1, p2
Step 4: Check both input is equal if yes, print “Tie” then go to step 9
Step 5: Check p1=”rock” and p2= “scissor” if yes, print “First player is winner” else print “second player is
winner” then go to step 9
Step 6: Check p1=” scissor” and p2= “paper” if yes, print “First player is winner” else print “second player is
winner” then go to step 9
Step 7: Check p1=”paper” and p2= “rock” if yes, print “First player is winner” else print “second player is
winner” then go to step 9
Step 8: Otherwise print “Invalid input”
Step 9: Stop
Program:
for i in range(3):
p1=input("First player:")
p2=input("Second player:")
if(p1==p2):
print("TIE")
elif(p1=='rock'):
if(p2=='scissor'):
print("first player is winner")
else:
print("Second player is winner")
elif(p1=='scissor'):
if(p2=='paper'):
print("First player is winner")
else:
print("second player is winner")
elif(p1=='paper'):
if(p2=='rock'):
print("first player is winner")
else:
print("second player is winner")
else:
print("Invalid input")
Output:
First player:rock
Second player:rock
TIE
First player:paper
Second player:paper
TIE
First player:rock
Second player:paper
Second player is winner
Result: Thus the python program is performed byconditional, control and looping statements using the Rock-
Paper-Scissor game is implemented.
TASK-3: Importing and creating python modules and packages in python program
Aim:
Importing and Creating Python modules and packages in python programming
Algorithm:
Step1: start
Step2: To create a package Cardpack
Step3: To create a module CardFun and import random fuction
Step 4: Assign a cards range.
Step 5: Call a module function.
Step 6: Display the random sample cards
Step 7: Stop
Program:
CardFun
import random
def func():
cards=[]
for i in range(1,53):
cards.append(i)
shuffled_cards = random.sample(cards, k=52)
print("\n\n",shuffled_cards,"\n\n")
Mymod.py
import CardFun
CardFun.func()
Output:
RESTART: C:\Users\Student.MAT2VC6833\AppData\Local\Programs\Python\Python311\Lib\site-packages\
CardPack\MyMod.py
[5, 24, 13, 22, 20, 41, 38, 51, 4, 7, 34, 49, 14, 50, 37, 40, 15, 35, 17, 18, 33, 39, 36, 42, 12, 6, 16, 19, 48, 29, 2,
27, 11, 31, 46, 28, 21, 32, 8, 25, 30, 23, 26, 10, 43, 47, 3, 44, 52, 1, 45, 9]
Result:
Thus the python program is performed by creating python module and packages in python program
TASK 4: Use various data types, list, tuples, sets and dictionary in python programming
AIM: To develop a python program which stores the details of the student using dictionary. The key of the
dictionary being a string and values being a tuple.
ALGORITHM:
Step 1: Start
Step 2: Take the number of the students from the user for whom the details have to be stored
Step 3: Take the necessary details from the user of students one by one
Step 4: Add the details to the dictionary with key being a unique id (Here, registration number) and
valuesbeing the details of the student (Here, name ad cgpa)
Step 5: Display the stored dictionary
Step 6: End
PROGRAM:
count = int(input("enter the number of students:"))
details= {}
for i in range(0,count):
print("\nEnter detailsof students",i+1)
reg_no=input("Registration no:")
name=input("Name:")
cgpa=input("gpa/cgpa:")
details[reg_no]=(name,cgpa)
print("\n",details)
OUTPUT:
RESULT:
Thus the python program which stores the details of the student using dictionary and the key of the dictionary
being a string and values being a tuple is performed.
Task 5: Implement various Searching and Sorting Operations in python programming
AIM:
Write a python program to find the highest and lowest mark using sorting method and find a particular mark in
the mark list.
Algorithm:
Step 1:Start
Step 2:Read the number of students ‘n’
Step 3: Repeat
Read the students marks in list
Until i<n
Step 4:Use the List sort method to sort the marks and print the lowest and highest mark
Step 5: Read the searching element ‘search’
Step 6:Repeat
if mark[i] == search then print the mark is present
else continue
until 1-n+1
Step:7 End
Program:
mark=[]
n=int(input("Enter number of student" ))
for i in range(1,n+1):
element=int(input("Enter students mark one by one"))
mark.append(element)
print("The entered Marks are",mark)
mark.sort()
print("Lowest mark of the class is ",mark[0])
print("Highest mark of the class is ",mark[len(mark)-1])
search=int(input("Enter the searching mark"))
for i in range(0,n+1):
if mark[i] == search:
print("Searching Mark is present")
break
else:
continue
Output:
Enter number of student5
Enter students mark one by one56
Enter students mark one by one23
Enter students mark one by one89
Enter students mark one by one70
Enter students mark one by one23
The entered Marks are [56, 23, 89, 70, 23]
Lowest mark of the class is 23
Highest mark of the class is 89
Enter the searching mark70
Searching Mark is person
RESULT:
Thus the python program to find the highest and lowest mark using sorting method and find a particular mark
was executed successfully.
TASK -6 Implement various txt/csv file operations
Aim:
To write a python program for creating and updating student registration details using txt file
operations.
Algorithm:
Step 1 Start
Step 2 Using open() method, Create and write text file “myfile.txt” with student details.
Step 3 Update the new registered student details using append operation in it.
Step 4 Open the file in read mode and using read() method print the student details.
Step 5 Using seek method print the particular student record.
Step 6 Using tell method print the current position of the file.
Step 7 Close the file.
Step 8 Stop.
Program:
file = open("student1.txt","w")
input1=input("Enter columns name\n")
file.write(input1)
file.write("\n")
n=int(input("Enter the no of students"))
for i in range(0,n+1):
input2=input("Enter students details with for new")
file.write(input2)
file.write("\n")
file=open("student1.txt","a")
input3=input("Enter updated students details\n")
file.write(input3)
file = open("student1.txt","r")
print("Student Details using Read function is: ")
print(file.read())
print("\n")
file.seek(0)
print( "The length of first line is: ")
line=file.readline()
len=len(line)
print(len)
file.seek(len+1)
print("Output of Readline(first student record) function is: ")
print(file.readline())
Result: Thus, the python program for creating and updating student registration details using txt file
operations was executed successfully.
Task 7 Utilizing ‘Functions’ concepts in Python Programming.
Aim:
To develop a Python program byUtilizing ‘Functions’ concepts in Python Programming.
Algorithm:
Step 1: Start
Step 2: Read the choice input value
Read the range of numbers input from the user for case 1 and case 2
Case 1: Find the even numbers in the range
Case 2: Find the odd numbers in the range
Case 3: Get a number from user to find positive or negative input
Step 3: Stop
Program:
choice = int(input("Enter your number between 1-3\n"))
for num in range(1,20):
match choice:
case 1:
def find_Even(num):
if(num%2==0):
print(num," Is an even")
find_Even(num);
case 2:
def find_Odd(num):
if(num%2!=0):
print(num," Is an odd")
find_Odd(num);
case 3:
a = float(input("Enter a number as input value: "))
def NumberCheck():
# Checking if the number is positive
if a > 0:
print("Number given by you is Positive")
# Checking if the number is negative
else:
print("Number given by you is negative")
# Printing result
NumberCheck();
break
Output:
Enter your number between 1-3
1
2 Is an even
4 Is an even
6 Is an even
8 Is an even
10 Is an even
12 Is an even
14 Is an even
16 Is an even
18 Is an even
Aim: To develop a python program to implement Multi-Threading concepts using threading module.
Algorithm:
Start 1: Start the program
Start 2: Import the threading module and time module
Start 3: Create the function name fun1, fun2
Start 4: start the thread module t1.start () and t2.start ()
Step 5: The function 1 and function 2 starts executes the iteration until the for loop ends
Step 6: Once the iteration is over it start print the thread name and value
Step 7: stop
Program:
import threading
import time
def fun1(s,name,n):
for i in range(s,n,2):
print(name,i)
time.sleep(2)
def fun2(s,name,n):
for i in range(s,n,2):
print(name,i)
time.sleep(1)
t1=threading.Thread(target=fun1,args=(1,"Thread1",10))
t2=threading.Thread(target=fun2,args=(0,"Thread2",10))
t1.start()
t2.start()
Output:
Thread1Thread2 10
Thread2 2
Thread1 3
Thread2 4
Thread2 6
Thread1 5
Thread2 8
Thread1 7
Thread1 9
Result: Thus the python program is implemented in Multi-Threading concepts using threading module.
TASK 9 Implement Exceptions and Exceptional handling in Python
AIM:
Write the python program to implement Exceptions and Exceptional handling in Python.
ALGORITHM:
STEP 1: Start.
STEP 2: Get the two input from the user inside the try block.
STEP 3: When the exception occurs the ValueError except block will execute otherwise else block
will execute.
STEP 4: To handle the exception the other try block is created inside the else.
STEP 5: When the exception occurs the ZeroDivisionError except block will execute
otherwise else block will execute
STEP 6: Stop.
PROGRAM:
try:
first_number = float(input("Enter the first number : "))
second_number = float(input("Enter the second number : "))
except ValueError:
print("Please enter a valid number")
else:
try:
result = first_number / second_number
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is ", result)
finally:
print("Program completed")
OUTPUT:
SAMPLE OUTPUT 1:
Enter the first number : 10
Enter the second number : A
Please enter a valid number
Program completed
SAMPLE OUTPUT 2:
Enter the first number : 10
Enter the second number : 0
Cannot divide by zero
Program completed
SAMPLE OUTPUT 3:
Enter the first number : 34
Enter the second number : 6
Result is 5.666666666666667
Program completed
RESULT:
Thus the program using exception handling has been done successfully.
Task 10: Use Matplotlib module for plotting in python.
Aim: Write a python code to plot the graph using matplotlib
Algorithm:
Step 1: start
Step 2: Give the x axis values and y axis values
Step 3 : Plot the values using the module
Step 4 : Lable the axis
Step 5 : Display the graph
Step 6 : Stop
PROGRAM
import matplotlib.pyplot as plt
x = [1,2,6]
y = [2,5,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My first graph!')
plt.show()
OUTPUT:
Output:
RESULT:
Thus the python program use pandas library to process the data frames in python successfully completed.
TASK-12 Tkinter module for UI design
Aim:
To develop UI design using tkinter module for age calculator.
Algorithm:
Step 1: Start.
Step 2: Import tkinter module and import datetime module from date package.
Step 3: Call the window using root.Tk() method and give the title and geometry.
Step 4: Write the function to calculate age.
Step 5: Assign label for name, year, month and age and give the box size using grid() method.
Step 6: Get the values using StringVar() method.
Step 7: Create Button to Calculate Age and call the method calculateage.
Step 8: End tinkter method using root.mainloop().
Step 9: End.
Program:
from tkinter import *
from datetime import date
root=Tk()
root.title("AGE-CALCULATOR")
root.configure(bg="#D5C6FF")
root.geometry("300x300")
def calculateage():
today = date.today()
birthDate=date(int(yearEntry.get()),int(monthEntry.get()),int(dayEntry.get()))
age=today.year-birthDate.year((today.month,today.day)<(birthDate.month,birthDate.day))
Label(text=f"{nameValue.get()} your age is {age}").grid(row =6,column =1)
Label(text = "Name:").grid(row =1,column =0,padx=90)
Label(text = "Year:").grid(row =2,column =0)
Label(text = "Month:").grid(row =3,column =0)
Label(text = "Day:").grid(row =4,column =0)
nameValue=StringVar()
yearValue=StringVar()
monthValue=StringVar()
dayValue=StringVar()
nameEntry=Entry(root,textvariable=nameValue)
yearEntry=Entry(root,textvariable=yearValue)
monthEntry=Entry(root,textvariable=monthValue)
dayEntry=Entry(root,textvariable=dayValue)
nameEntry.grid(row =1,column =1)
yearEntry.grid(row =2,column =1)
monthEntry.grid(row =3,column =1)
dayEntry.grid(row =4,column =1)
Button(text="Calculate Age",command=calculateage).grid(row=5,column=1,pady=10)
root.mainloop()
Output:
Result:
Thus the python program to develop UI design using tkinter module for age calculator was executed
successfully.
Task 13 Stimulating gaming concept using pygame
Aim:
To develop a Python program by stimulating gaming concept using pygame
Algorithm:
Step 1:Start
Step 2:Import and initialize the pygame library.
Step 3:Set up a list to create a square window with 500 pixels on each side of your program as display
window.
Step 4:Repeat steps 5 to 8 until the condition true
Step 5:Create pygame events for the game loop
Step 6:Fills the window with a solid color
Step 7:Draws a circle in the window
Step 8:Updates the contents of the display to the screen
Step 9:Exits pygame
Program:
# Simple pygame program
# Import and initialize the pygame library
import pygame
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([500, 500])
# Run until the user asks to quit
running = True
while running:
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the background with white
screen.fill((255, 255, 255))
# Draw a solid blue circle in the center
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
# Flip the display
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
Output:
Result:
Thus the python program is performed by stimulating gaming concept using pygame.
CASE STUDY
Task 14: Build any one classical data structure using python.
Mr. bean maintaining a book store in university campus.0 He wants to maintain all the available book titles in
tree structure in order to search efficiently in memory. He wants to create a tree with the book titles with
following properties.
o Each node needs to have book title and instances
o Each parent node having larger than left sub tree and smaller than right sub tree by means of
ASCII value.
o Each node having at most two children
o The height difference between left and right subtree is at most 1 in any node.
Program:
class Node:
def __init__(self, key, instance):
self.left = None
self.right = None
self.key = key
self.instance = instance
class BST:
def __init__(self):
self.root = None
def insert(self, key, instance):
if self.root is None:
self.root = Node(key, instance)
else:
self._insert_helper(self.root, key, instance)
def _insert_helper(self, node, key, instance):
if key < node.key:
if node.left is None:
node.left = Node(key, instance)
else:
self._insert_helper(node.left, key, instance)
elif key > node.key:
if node.right is None:
node.right = Node(key, instance)
else:
self._insert_helper(node.right, key, instance)
else:
node.instance += instance
def print_inorder(self):
if self.root is not None:
self._print_inorder_helper(self.root)
def _print_inorder_helper(self, node):
if node.left is not None:
self._print_inorder_helper(node.left)
print(node.key, node.instance)
if node.right is not None:
self._print_inorder_helper(node.right)
To insert a new book title with its instances, we can use the `insert` method of the `BST` class. To update the
tree after each borrowing and return process, we can also use the `insert` method. If the book title is already in
the tree, we can add the instances to the existing node instead of creating a new node. To print the titles along
with its instances in alphabetical order, we can use the `print_inorder` method of the `BST` class.
For example, here's how we can use this implementation:
python
bst = BST()
bst.insert("The Great Gatsby", 1)
bst.insert("1984", 2)
bst.insert("Brave New World", 3)
bst.insert("The Catcher in the Rye", 1)
bst.insert("To Kill a Mockingbird", 2)
bst.insert("The Great Gatsby", 1)
bst.print_inorder()
Output:
1984 2
Brave New World 3
The Catcher in the Rye 1
The Great Gatsby 2
To Kill a Mockingbird 2
Aim:
To build a classical data structure using python to maintain a bookstore in the university campus
Algorithm:
Step 1:Start
Step 2:Import the module sys
Step 3:Declare the class Library
Step 4:Declare the library name as “lname” and books list as “listofbooks”
Step 5:Define displaybooks(),addbooks(),lendbooks(),returnbooks()functions for the various operations to be performed
in the library
Program:
from tkinter import *
import backend
window = Tk()
def get_selected_row(event):
try:
global select_tup
index=list1.curselection()[0]
select_tup = list1.get(index)
e1.delete(0,END)
e1.insert(END, select_tup[1])
e2.delete(0,END)
e2.insert(END, select_tup[2])
e3.delete(0,END)
e3.insert(END, select_tup[3])
e4.delete(0,END)
e4.insert(END, select_tup[4])
except IndexError:
pass
def view_command():
list1.delete(0,END)
for row in backend.view():
list1.insert(END, row)
def search_command():
list1.delete(0,END)
for row in backend.search(title_text.get(),author_text.get(),year_text.get(), isbn_text.get()):
list1.insert(END,row)
def add_book():
backend.insert(title_text.get(),author_text.get(),year_text.get(), isbn_text.get())
list1.delete(0,END)
list1.insert(END,(title_text.get(),author_text.get(),year_text.get(), isbn_text.get()))
def delete_book():
backend.delete(select_tup[0])
def update_book():
backend.update(select_tup[0], title_text.get(),author_text.get(),year_text.get(), isbn_text.get())
window.wm_title("Book Store")
l1 = Label(window, text="Title")
l1.grid(row=0,column=0)
l2 = Label(window, text="Auther")
l2.grid(row=0,column=2)
l3 = Label(window, text="Year")
l3.grid(row=1,column=0)
l4 = Label(window, text="ISBN")
l4.grid(row=1,column=2)
title_text = StringVar()
e1 = Entry(window, textvariable= title_text)
e1.grid(row=0, column=1)
author_text = StringVar()
e2 = Entry(window, textvariable= author_text)
e2.grid(row=0, column=3)
year_text = StringVar()
e3 = Entry(window, textvariable= year_text)
e3.grid(row=1, column=1)
isbn_text = StringVar()
e4 = Entry(window, textvariable= isbn_text)
e4.grid(row=1, column=3)
list1.bind("<<ListboxSelect>>", get_selected_row)
sb1 =Scrollbar(window)
sb1.grid(row=2, column=2 ,rowspan = 6)
list1.configure(yscrollcommand=sb1.set)
sb1.configure(command=list1.yview)
|| Main menu ||
1. To view the books available to you, please enter "p"
2. To lend books from this library, please enter "l"
3. To return books, Please enter "r"
4. To add books to the library shelf, please enter "a"
5. To quit or exit, please enter "x"
Please Enter your input here: p
|| Main menu ||
1. To view the books available to you, please enter "p"
2. To lend books from this library, please enter "l"
3. To return books, Please enter "r"
4. To add books to the library shelf, please enter "a"
5. To quit or exit, please enter "x"
Please Enter your input here: l
Enter your name: Abi
Enter the name of the book you want to lend: PSQT
Book has been successfully lend.
For continuing with main menu enter 'c' or exit enter 'x'
Enter: c
|| Main menu ||
1. To view the books available to you, please enter "p"
2. To lend books from this library, please enter "l"
3. To return books, Please enter "r"
4. To add books to the library shelf, please enter "a"
5. To quit or exit, please enter "x"
Please Enter your input here: r
Enter the book name which you want to return: PSQT
Lend details:
This book is lend by Abi.
If you want to return this book, enter "y" otherwise, press any key to skip.
Enter: y
Thank you! Your book has been returned.
|| Main menu ||
1. To view the books available to you, please enter "p"
2. To lend books from this library, please enter "l"
3. To return books, Please enter "r"
4. To add books to the library shelf, please enter "a"
5. To quit or exit, please enter "x"
Please Enter your input here: a
Add the book to the Book lists:
Wings of Fire
"Wings of Fire" is added to the list.
For continuing with main menu enter 'c' or exit enter 'x'
Enter: c
|| Main menu ||
1. To view the books available to you, please enter "p"
2. To lend books from this library, please enter "l"
3. To return books, Please enter "r"
4. To add books to the library shelf, please enter "a"
5. To quit or exit, please enter "x"
Please Enter your input here: p
Result:
Python program using Data structures to maintain a bookstore in the university campus is computed
Task 16 Hotel Management System Python Tkinter GUI
class HOTEL_MANAGEMENT:
def __init__(self):
root = Tk()
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#ffffff' # X11 color: 'white'
_ana1color = '#ffffff' # X11 color: 'white'
_ana2color = '#ffffff' # X11 color: 'white'
font14 = "-family {Segoe UI} -size 15 -weight bold -slant " \
"roman -underline 0 -overstrike 0"
font16 = "-family {Swis721 BlkCn BT} -size 40 -weight bold " \
"-slant roman -underline 0 -overstrike 0"
font9 = "-family {Segoe UI} -size 9 -weight normal -slant " \
"roman -underline 0 -overstrike 0"
root.geometry("963x749+540+110")
root.title("HOTEL MANAGEMENT")
root.configure(background="#d9d9d9")
root.configure(highlightbackground="#d9d9d9")
root.configure(highlightcolor="black")
self.menubar = Menu(root,font=font9,bg=_bgcolor,fg=_fgcolor)
root.configure(menu = self.menubar)
self.Frame1 = Frame(root)
self.Frame1.place(relx=0.02, rely=0.03, relheight=0.94, relwidth=0.96)
self.Frame1.configure(relief=GROOVE)
self.Frame1.configure(borderwidth="2")
self.Frame1.configure(relief=GROOVE)
self.Frame1.configure(background="#d9d9d9")
self.Frame1.configure(highlightbackground="#d9d9d9")
self.Frame1.configure(highlightcolor="black")
self.Frame1.configure(width=925)
self.Message6 = Message(self.Frame1)
self.Message6.place(relx=0.09, rely=0.01, relheight=0.15, relwidth=0.86)
self.Message6.configure(background="#d9d9d9")
self.Message6.configure(font=font16)
self.Message6.configure(foreground="#000000")
self.Message6.configure(highlightbackground="#d9d9d9")
self.Message6.configure(highlightcolor="black")
self.Message6.configure(text='''WELCOME''')
self.Message6.configure(width=791)
self.Button2 = Button(self.Frame1)
self.Button2.place(relx=0.18, rely=0.17, height=103, width=566)
self.Button2.configure(activebackground="#d9d9d9")
self.Button2.configure(activeforeground="#000000")
self.Button2.configure(background="#d9d9d9")
self.Button2.configure(disabledforeground="#bfbfbf")
self.Button2.configure(font=font14)
self.Button2.configure(foreground="#000000")
self.Button2.configure(highlightbackground="#d9d9d9")
self.Button2.configure(highlightcolor="black")
self.Button2.configure(pady="0")
self.Button2.configure(text='''1.CHECK INN''')
self.Button2.configure(width=566)
self.Button2.configure(command=click_checkinn)
self.Button3 = Button(self.Frame1)
self.Button3.place(relx=0.18, rely=0.33, height=93, width=566)
self.Button3.configure(activebackground="#d9d9d9")
self.Button3.configure(activeforeground="#000000")
self.Button3.configure(background="#d9d9d9")
self.Button3.configure(disabledforeground="#bfbfbf")
self.Button3.configure(font=font14)
self.Button3.configure(foreground="#000000")
self.Button3.configure(highlightbackground="#d9d9d9")
self.Button3.configure(highlightcolor="black")
self.Button3.configure(pady="0")
self.Button3.configure(text='''2.SHOW GUEST LIST''')
self.Button3.configure(width=566)
self.Button3.configure(command=click_list)
self.Button4 = Button(self.Frame1)
self.Button4.place(relx=0.18, rely=0.47, height=93, width=566)
self.Button4.configure(activebackground="#d9d9d9")
self.Button4.configure(activeforeground="#000000")
self.Button4.configure(background="#d9d9d9")
self.Button4.configure(disabledforeground="#bfbfbf")
self.Button4.configure(font=font14)
self.Button4.configure(foreground="#000000")
self.Button4.configure(highlightbackground="#d9d9d9")
self.Button4.configure(highlightcolor="black")
self.Button4.configure(pady="0")
self.Button4.configure(text='''3.CHECK OUT''')
self.Button4.configure(width=566)
self.Button4.configure(command=click_checkout)
self.Button5 = Button(self.Frame1)
self.Button5.place(relx=0.18, rely=0.61, height=103, width=566)
self.Button5.configure(activebackground="#d9d9d9")
self.Button5.configure(activeforeground="#000000")
self.Button5.configure(background="#d9d9d9")
self.Button5.configure(disabledforeground="#bfbfbf")
self.Button5.configure(font=font14)
self.Button5.configure(foreground="#000000")
self.Button5.configure(highlightbackground="#d9d9d9")
self.Button5.configure(highlightcolor="black")
self.Button5.configure(pady="0")
self.Button5.configure(text='''4.GET INFO OF ANY GUEST''')
self.Button5.configure(width=566)
self.Button5.configure(command=click_getinfo)
self.Button6 = Button(self.Frame1)
self.Button6.place(relx=0.18, rely=0.77, height=103, width=566)
self.Button6.configure(activebackground="#d9d9d9")
self.Button6.configure(activeforeground="#000000")
self.Button6.configure(background="#d9d9d9")
self.Button6.configure(disabledforeground="#bfbfbf")
self.Button6.configure(font=font14)
self.Button6.configure(foreground="#000000")
self.Button6.configure(highlightbackground="#d9d9d9")
self.Button6.configure(highlightcolor="black")
self.Button6.configure(pady="0")
self.Button6.configure(text='''5.EXIT''')
self.Button6.configure(width=566)
self.Button6.configure(command=quit)
root.mainloop()
if __name__ == '__main__':
GUUEST=HOTEL_MANAGEMENT()
Output:
Result:Thus, hotel management system implemented using Tkinter.
Task 17 Polls game design using pygame
Aim:
To design 8 Ball pool game interface using Pygame module in python programming.
Algorithm:
Step 1: Start.
Step 2: Import the module pygame, sys, math, random.
Step 3: Initialize the pygame window.
Step 4: Declare the specifications for ball, stick and background.
Step 5: Declare the class Ball with the objects colour, angle, speed, ballNum.
Step 6: Draw balls on display window using the defined draw function.
Step 7: Move the balls in the screen using the move function.
Step 8: Define the Class Pockets.
Step 9: Declare the necessary classes and the functions required (class names and function names).
Step 10: End
Program Code:
import pygame
import sys
from math import *
import random
pygame.init()
width = 660
height = 360
outerHeight = 400
margin = 30
display = pygame.display.set_mode((width, outerHeight))
pygame.display.set_caption("8 Ball Pool")
clock = pygame.time.Clock()
colors = [yellow, blue, red, purple, orange, green, brown, black, yellow, blue, red, purple, orange, green,
brown]
balls = []
noBalls = 15
radius = 10
friction = 0.005
# Ball Class
class Ball:
def __init__(self, x, y, speed, color, angle, ballNum):
self.x = x + radius
self.y = y + radius
self.color = color
self.angle = angle
self.speed = speed
self.ballNum = ballNum
self.font = pygame.font.SysFont("Agency FB", 10)
# Pocket Class
class Pockets:
def __init__(self, x, y, color):
self.r = margin/2
self.x = x + self.r + 10
self.y = y + self.r + 10
self.color = color
balls = ballsCopy[:]
# Checks Collision
def collision(ball1, ball2):
dist = ((ball1.x - ball2.x)**2 + (ball1.y - ball2.y)**2)**0.5
if dist <= radius*2:
return True
else:
return False
balls[i].x += (balls[i].speed)*sin(radians(angle))
balls[i].y -= (balls[i].speed)*cos(radians(angle))
cueBall.x -= (cueBall.speed)*sin(radians(angle))
cueBall.y += (cueBall.speed)*cos(radians(angle))
balls[i].x += (balls[i].speed)*sin(radians(angle))
balls[i].y -= (balls[i].speed)*cos(radians(angle))
balls[j].x -= (balls[j].speed)*sin(radians(angle))
balls[j].y += (balls[j].speed)*cos(radians(angle))
def border():
pygame.draw.rect(display, gray, (0, 0, width, 30))
pygame.draw.rect(display, gray, (0, 0, 30, height))
pygame.draw.rect(display, gray, (width - 30, 0, width, height))
pygame.draw.rect(display, gray, (0, height - 30, width, height))
def score():
font = pygame.font.SysFont("Agency FB", 30)
def reset():
global balls, noBalls
noBalls = 15
balls = []
s = 70
balls.append(b1)
balls.append(b2)
balls.append(b3)
balls.append(b4)
balls.append(b5)
balls.append(b6)
balls.append(b7)
balls.append(b8)
balls.append(b9)
balls.append(b10)
balls.append(b11)
balls.append(b12)
balls.append(b13)
balls.append(b14)
balls.append(b15)
def gameOver():
font = pygame.font.SysFont("Agency FB", 75)
if len(balls) == 0:
text = font.render("You Won!", True, (133, 193, 233))
else:
text = font.render("You Lost! Black in Hole!", True, (241, 148, 138))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
close()
if event.key == pygame.K_r:
poolTable()
display.blit(text, (50, height/2))
pygame.display.update()
clock.tick()
def close():
pygame.quit()
sys.exit()
# Main Function
def poolTable():
loop = True
reset()
noPockets = 6
pockets = []
p1 = Pockets(0, 0, black)
p2 = Pockets(width/2 - p1.r*2, 0, black)
p3 = Pockets(width - p1.r - margin - 5, 0, black)
p4 = Pockets(0, height - margin - 5 - p1.r, black)
p5 = Pockets(width/2 - p1.r*2, height - margin - 5 - p1.r, black)
p6 = Pockets(width - p1.r - margin - 5, height - margin - 5 - p1.r, black)
pockets.append(p1)
pockets.append(p2)
pockets.append(p3)
pockets.append(p4)
pockets.append(p5)
pockets.append(p6)
start = 0
end = 0
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
close()
if event.key == pygame.K_r:
poolTable()
if event.type == pygame.MOUSEBUTTONDOWN:
start = [cueBall.x, cueBall.y]
x, y = pygame.mouse.get_pos()
end = [x ,y]
dist = ((start[0] - end[0])**2 + (start[1] - end[1])**2)**0.5
force = dist/10.0
if force > 10:
force = 10
cueStick.applyForce(cueBall, force)
display.fill(background)
cueBall.draw(cueBall.x, cueBall.y)
cueBall.move()
cueStick.draw(cueBall.x, cueBall.y)
for i in range(len(balls)):
balls[i].draw(balls[i].x, balls[i].y)
for i in range(len(balls)):
balls[i].move()
checkCollision()
checkCueCollision(cueBall)
border()
for i in range(noPockets):
pockets[i].draw()
for i in range(noPockets):
pockets[i].checkPut()
score()
pygame.display.update()
clock.tick(60)
poolTable()
Output:
Result:
Thus the 8 Ball pool game interface using Pygame module in python programming is implemented.
AIM:
To build a python programming in angry bird game using pygame
ALGORITHM:
Step1:start
Step2:import pygame, sys, random, math
Step3: import physics_engine, objects, maps, interface
Step4: initalise pygame
Step5: define width as 1500,height as 700 and display it
Step 6: display the supporting modules
Step 7: call close () ,start_game()
Step8:call GAME()
Step9: stop
FUNCTION GAME
Step1: set a font colour,size for welcome ,start,exitC
Step2:while true
For event in pygame.event.get
If event ==quit
Quit
If event ==start
Start_game
Step3: draw start,welcome,exit
Step 4:end
PROGRAM:
import pygame
import sys
import random
from math import *
import physics_engine
import objects
import maps
import interface
pygame.init()
width = 1500
height = 700
display = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
physics_engine.init(display)
objects.init(display)
maps.init(display)
interface.init(display)
def close():
pygame.quit()
sys.exit()
def start_game(map):
map.draw_map()
def GAME():
map = maps.Maps()
start = interface.Button(500, 400, 300, 100, start_game, (244, 208, 63), (247, 220, 111))
start.add_text("START GAME", 60, "Fonts/arfmoochikncheez.ttf", background)
exit = interface.Button(1000, 400, 300, 100, close, (241, 148, 138), (245, 183, 177))
exit.add_text("QUIT", 60, "Fonts/arfmoochikncheez.ttf", background)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
close()
if event.type == pygame.MOUSEBUTTONDOWN:
if exit.isActive():
exit.action()
if start.isActive():
start_game(map)
display.fill(background)
start.draw()
exit.draw()
welcome.draw()
mandav.draw()
pygame.display.update()
clock.tick(60)
GAME()
OUTPUT: