0% found this document useful (0 votes)
7 views84 pages

Python Programming Experiments List

Uploaded by

venulogics2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views84 pages

Python Programming Experiments List

Uploaded by

venulogics2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

List of Experiments

Page
S. No. Program Date
No.
Python program to implement the following using recursion:

1 a) Factorial of a given number.


b) Fibonacci series up to n terms.
c) Sum of digits of given number.

Python program to implement the following using Modules:


a) Generate a random password with following conditions:
i) Length of the password should not exceed 10 characters long
ii) Starts with an alphabet or underscore.
iii) It must be at least two uppercase letters, one digit and one special
character ( $, #, @, _)
2 b) Generate a random date between two given dates.
c) Print 12 fixed dates from specified date where the difference between two
dates is 20.
d) Calculate your age (years, months and remaining days) based on the given
date.
e) Find all integers, floating point numbers from given paragraph and print
their sum.
f) Count the number of words ending with s or S in a given paragraph.

Python program to read a text file named “[Link]” and display the following:
a) The words start with t and a (or) T and A.
b) Even length words in a given file.
c) Python program to read a binary file named “[Link]” has structure
3 [ bookname, book no., author, price ]
Write a user defined function createfile() to input data for a record and
add to “[Link]”
Write a user defined function countRec(author) which accepts author
name as parameter and count the [Link] books by the given author are
stored in binary file “[Link]” and return result.

Python program to demonstrate the following using OOP concepts:


a) Bank Management System with following modules:
i) Create account ii) Deposit Money
4 iii) Withdraw Money iv) Check Balance v) Mini Statement
b) Library Management System with following modules:
i) Add Book details ii) View Book details
iii) Delete Book details iv) Search Book details
Page
S. No. Program Date
No.
Python program to implement the following data structures using list:
a) Stack with following operations:
i) push ii) pop iii) display

b) Queue with following operations:


5
i) enqueue ii) dequeue iii) display
c) Single Linked List with following Operations:
i) Create ii) insert_at_begin iii) insert_at_end
iii) delete_at_begin iv) delete_at_end
Python program to develop a menu driven program which consists of
6 General-purpose calculator, Scientific calculator and Advanced Scientific
calculator using multi-level inheritance.
Python program to implement Employee Management System / Student
Mangement System using Sqlite3 with following Operations:
7 i) Create database ii) Insert Record iii) Delete record

iv) Update record v) Search record vi) Display record


Python Program to read an excel file named "[Link]" and perform
the following:
i) Print sum, mean, maximum and minimum marks of a student.
ii) Print student record based on given register number.
8
iii) Print the student records based given range of marks.
iv) Print the student record based on the name starts with "S or s"
v) Sort the student records based on the register number.
vi) Merge the contents of two sheets into another excel file.

Python Program to implement a Simple Game. (Tic Tac Toe or Number


9
Game or Quiz or Puzzle or Etc...)

Python program to implement a simple calculator with a GUI interface


10
using the tkinter module.
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Write a python programme to find the factorial of a given number using recursion ?

Source code:

(a) # -*- coding: utf-8 -*-

"""

Created on Tue Mar 11 08:14:22 2025

@author: it203

"""

def fact(n):

if n < 0:

print("Factorial is not supported for negative numbers.")

return None

elif n == 0:

return 1

else:

return n * fact(n - 1)

while True:

try:

n = int(input("Enter the value of n: "))

result = fact(n)

if result is not None:

print("Factorial of the given number is:", result)

except ValueError:

print("Please enter a valid integer.")

c = input("\nDo you want to continue? (y/n): ")

if [Link]() == 'n':

break

1
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Output:

Aim: Write a python programme to find the fibanocci series upto n terms using recursion ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Mar 11 08:23:18 2025

@author: it203

"""

def fib(n):

if n<=1:

return 1

else:

return fib(n-1)+fib(n-2)

while True:

n=int(input("Enter n value"))

print("Fibnacci series: ")

print(0,end=" ")

for i in range(100):

if fib(i)<=n:

print(fib(i),end=" ")

else:

2
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

break

c=input("\ndo you want continue y/n:")

if c=='n' or c=='N':

break

Output:

Aim: Write a python programme to find the given number is palindrome or not using
recursion ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Mar 11 08:43:07 2025

@author: it203

"""

def pal(n, rev=0):

if n == 0:

return rev

else:

rem = n % 10

rev = rev * 10 + rem

return pal(n // 10, rev)

while True:

3
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

num = int(input("Enter the number: "))

if num == pal(num):

print(num, "is a palindrome")

else:

print(num, "is not a palindrome")

c = input("\nDo you want to continue (y/n): ")

if [Link]() == 'n':

break

Output:

Aim:

(A) Generate a random password with their following conditions:


(i)password must contain the 2 uppercase letters.
(ii)password must contain the 1 digit and 1 specilal character.
(iii)password must be 10 characters length .
(B) Generate random dates between two days .
(C) Print 12 fixed dates from a specified date,where difference between two days is 20.
(D) Calculate your age
(E) Find all integers and floating point numbers in the given paragraph & print their sum.
(F) Count the [Link] words ends with small “s” or capitals “S” .Dsiplay their words in
given format a given string occurrence ?

4
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Generate a random password with their following conditions:

(i)password must contain the 2 uppercase letters.


(ii)password must contain the 1 digit and 1 specilal character.
(iii)password must be 10 characters length .

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 15 07:36:04 2025

@author: it203

"""

while True:

import random

import string

password=string.ascii_letters+[Link]+[Link]

print(password)

password=[Link](string.ascii_letters,6)

password+=[Link](string.ascii_letters.upper(),2)

password+=[Link]([Link])

password+=[Link]([Link])

print("password is:",password)

pwd="".join(password)

print("updated password is:",pwd)

c=input("\ndo you want continue y/n:")

if c=='n' or c=='N':

break

5
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Output:

Aim: Write a python programme to generate the random days between the two days ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 15 08:22:48 2025

@author: it203

"""

while True:

from datetime import timedelta,datetime

sd=input("enter starting date(dd-mm-yy)")

sd1=[Link](sd,"%d-%m-%y")

print("starting date is",sd1)

ed=input("enter ending date(dd-mm-yy)")

ed1=[Link](ed,"%d-%m-%y")

print("ending date is",ed1)

print("dates between two days\n",sd1)

while sd1 < ed1 - timedelta(days=1):

sd1+=timedelta(days=1)

print(sd1)

6
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

c = input("\nDo you want to continue (y/n): ")

if [Link]() == 'n':

break

Output:

Aim: Write a python programme to Print 12 fixed dates from a specified date,where
difference between two days is 20.

Source code:

# -*- coding: utf-8 -*-

"""

Created on Wed Apr 23 21:36:14 2025

@author: it203

"""

while True:

from datetime import timedelta,datetime

d=input("enter any date(dd-mm-yyyy)")

d1=[Link](d,"%d-%m-%Y")

print("given date is:",d1)

print("12 fixed dates from specified date is",d1)

for i in range(12):

7
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

d1+=timedelta(days=20)

print(d1)

c = input("\nDo you want to continue (y/n): ")

if [Link]() == 'n':

break

Output:

Aim: Write a python programme to demonstrate Calculate your age

Source code:

# -*- coding: utf-8 -*-

"""

Created on Mon May 5 07:13:30 2025

@author: it203

"""

while True:

8
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

from datetime import datetime

d1=input("enter date(dd-mm-yyyy):")

d1=[Link](d1,"%d-%m-%Y")

d=[Link]()

d2=(d-d1).days

y=d2//365

m=(d2-(y)*365)//30

d3=(d2-(y*365))-(m*30)

print("your age is",y,"years",m,"months",d3,"days")

c=input("\n continue y/n:")

if c=="n" or c=="N":

break

Output:

Aim: Write a python programme to Find all integers and floating point numbers in the given
paragraph & print their sum.

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 29 07:29:32 2025

@author: it203

9
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

"""

while True:

import re

str1 = input("Enter the string contains numbers and letters:")

l = [Link](r"\d+", str1)

floats = [float(num) for num in l]

total_sum = sum(floats)

print("extracted numbers:", floats)

print("sum of extracted numbers:", total_sum)

c = input("\nDo you want to continue (y/n): ")

if [Link]() == 'n':

break

Output:

Aim: Write a python programme Count the [Link] words ends with small “s” or capitals
“S” and Display their words in given format a given string occurrence ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 29 07:34:12 2025

@author: it203

10
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

"""

import re

while True:

str = input("Enter a string: ")

words = [Link]()

matched_words = []

for word in words:

if [Link]('s') or [Link]('S'):

matched_words.append(word)

print("\nWords ending with 's' or 'S':")

print("\nTotal count:", len(matched_words))

c = input("\nDo you want to continue (y/n)? ")

if [Link]() == 'n':

break

Output:

Aim: Write a python programme to create filename “[Link]” write some content and display
their content from the file ?

Source code:

# -*- coding: utf-8 -*-

"""

11
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Created on Fri Apr 25 21:16:26 2025

@author: it203

"""

f1=open("[Link]","w")

str1="hello this is eswar reddy ambati"

[Link](str1)

f1=open("[Link]","r")

r=[Link]()

print(r)

[Link]()

Output:

Aim: Write a python programme to read a text file named “[Link]” and displays the
following?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Fri Apr 25 21:16:26 2025

"""

f=open("[Link]","r")

s=[Link]()

print(s)

s1=[Link](" ")

print(s1)

12
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

for i in s1:

if i[0]=='T' or i[0]=='t' or i[0]=='A' or i[0]=='a':

print(i)

else:

continue

Output:

Aim: Write a python programme to read a text file named “[Link]” and displays the
following and Even length words are in the file ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Mon Apr 28 14:36:28 2025

@author: it203

"""

import re

f=open("[Link]","w")

[Link]("hello this is eswarreddy ambati from bapatla enginering college")

f=open("[Link]","r")

str=[Link]()

print("The content in the file is:",str)

str1=[Link]()

13
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("The even length words are:")

for i in str1:

if len(i) % 2==0:

print(i)

Output:

Aim: Write a python programme to read a binary file named “[Link]” has
structure[bookname,bookno,author,price]

(i)Write a user defined function createfile() to input data for a record on add to
“[Link]”?

(ii)Write a user defined function count_rec(author) which accepts authorname

as parameter and count the no of books by the author in a binary file “[Link]” ?

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 22 08:58:19 2025

@author: it203

"""

import pickle

def createfile():

f=open("[Link]", "ab")

bname = input("Enter the book name: ")

14
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

bno = int(input("Enter the book number: "))

author = input("Enter the author name: ")

price = float(input("Enter the price of the book: "))

record = [bname, bno, author, price]

[Link](record, f)

print("Book record saved.\n")

def record_count():

a = input("Enter the author name to search: ")

count = 0

try:

f=open("[Link]", "rb")

while True:

try:

record = [Link](f)

if record[2].strip().lower() == [Link]().lower():

count += 1

except EOFError:

break

except Exception as e:

print("Error reading file:", e)

return

if count == 0:

print("No books found for the author:", a)

else:

print(f"Total books by '{a}': {count}")

while True:

createfile()

15
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

ch = input("Do you want to add another book? (y/n): ")

if [Link]() == 'n':

break

record_count()

Output:

Aim:Write a python programme to demonstrate the opps concepts ?

(A) Create a bank account management system with following functions:

(i)create account

(ii)deposit amount

(iii)withdraw amount

(iv)mini statement

(v)check balance

vi)count(no of bank accounts)

16
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

(A)Source code:

# -*- coding: utf-8 -*-

"""

Created on Wed Apr 30 15:48:29 2025

@author: it203

"""

import random

from datetime import datetime

class BANK:

def __init__(self):

[Link] = "BEC"

[Link] = {}

[Link] = []

def create(self):

name = input("Enter account holder's name: ")

accno = [Link](100000, 100999)

while True:

balance = int(input("Enter initial balance (min: Rs.500): "))

if balance < 500:

print("Please enter a balance of Rs.500 or more.")

else:

[Link][accno] = [name, balance]

print("Account created successfully at ", [Link]())

print("Your Account Number is " + str(accno))

print("Your Balance is Rs. " + str(balance))

[Link]((name, accno, balance, "Account Created")) # Log the


creation transaction

17
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

break

def deposit(self):

accno = int(input("Enter Account number to deposit: "))

if accno in [Link]:

p = input("Enter the password for Account number: ")

if p == [Link]:

amount = int(input("Enter the amount to be deposited: "))

[Link][accno][1] += amount # Update the balance

print("Deposited Successfully!")

[Link](([Link][accno][0], accno, amount, "Deposit")) #


Log the deposit transaction

else:

print("Incorrect password.")

else:

print("Invalid account number.")

def withdraw(self):

accno = int(input("Enter the Account number to withdraw: "))

if accno in [Link]:

p = input("Enter the password for Account number: ")

if p == [Link]:

amount = int(input("Enter the amount to withdraw: "))

if [Link][accno][1] < amount:

print("Insufficient Balance")

else:

[Link][accno][1] -= amount # Update the balance

print("Withdraw successful!")

[Link](([Link][accno][0], accno, amount,


"Withdrawal")) # Log the withdrawal transaction

18
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

else:

print("Incorrect password.")

else:

print("Invalid account number.")

def check_balance(self):

accno = int(input("Enter the account number to check the balance: "))

if accno in [Link]:

p = input("Enter the password for account number: ")

if p == [Link]:

print("Your balance is Rs. " + str([Link][accno][1]))

else:

print("Incorrect password.")

else:

print("Invalid account number.")

def mini_statement(self):

accno = int(input("Enter the Account number to view mini statement: "))

if accno in [Link]:

print("\nMini Statement for Account " + str(accno))

print("Account Holder: " + [Link][accno][0])

print("Balance: Rs. " + str([Link][accno][1]))

print("Recent Transactions:")

for transaction in reversed([Link]):

if transaction[1] == accno:

print(transaction[3] + " of Rs. " + str(transaction[2]) + " on " +


str([Link]()))

print()

else:

19
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Invalid account number.")

def display(self):

print("\nList of Accounts:")

for accno, details in [Link]():

print("Account Number: " + str(accno) + ", Name: " + details[0] + ", Balance: Rs. " +
str(details[1]))

print()

obj = BANK()

while True:

print("\n1. Create Account\n2. Deposit\n3. Withdraw\n4. Mini Statement\n5. Check


Balance\n6. Display Accounts\n7. Exit")

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

if choice == 1:

[Link]()

elif choice == 2:

[Link]()

elif choice == 3:

[Link]()

elif choice == 4:

obj.mini_statement()

elif choice == 5:

obj.check_balance()

elif choice == 6:

[Link]()

elif choice == 7:

print("Exiting. Thank you for banking with us!")

break

else:

20
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Invalid choice. Please try again.")

Output:

21
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

22
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

23
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim:Write a python programme to demonstrate the opps concepts ?

(A) Create a library management system with following functions:

(i)create

(ii)delete

(iii)update

(iv)search

(v)display

# -*- coding: utf-8 -*-

"""

Created on Mon Apr 28 15:10:54 2025

@author: it203

"""

class LIBRARY:

def __init__(self):

[Link] = ""

[Link] = 0

[Link] = ""

[Link] = 0.0

[Link] = ""

def create(self):

[Link] = input("Enter the book name: ")

[Link] = int(input("Enter the book number: "))

[Link] = input("Enter the author name: ")

[Link] = float(input("Enter the price: "))

[Link] = input("Enter the publisher's name: ")

[Link](self)

24
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Book record saved.\n")

def delete(self):

bno = int(input("Enter the book number to delete: "))

for i in l:

if [Link] == bno:

[Link](i)

print("Book has been deleted sucessfully.\n")

return

print("Book not found.\n")

def update(self):

bno = int(input("Enter the book number to update: "))

for i in l:

if [Link] == bno:

[Link] = input("Enter the new book name: ")

[Link] = input("Enter the new author name: ")

[Link] = float(input("Enter the new price: "))

[Link] = input("Enter the new publisher's name: ")

print("Book record updated.\n")

return

print("Book not found.\n")

def search(self):

bno = int(input("Enter the book number to search: "))

for i in l:

print("Book Found:\n")

if [Link] == bno:

print([Link],[Link],[Link],[Link])

return

25
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Book with number " + str(bno) + " not found.\n")

def display(self):

if len(l) == 0:

print("No books available in the library.\n")

return

print("Displaying all books:")

print("Book No Name Author Price Publisher")

for i in l:

print([Link],[Link],[Link],[Link],[Link])

print()

l=[]

while True:

print("1. Create\n2. Delete\n3. Update\n4. Search\[Link]\n6. Exit")

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

obj = LIBRARY()

if ch == 1:

[Link]()

elif ch == 2:

[Link]()

elif ch == 3:

[Link]()

elif ch == 4:

[Link]()

elif ch == 5:

[Link]()

elif ch == 6:

print("You are exiting...")

26
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

break

else:

print("Invalid choice, please enter a valid option.\n")

Output:

27
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

28
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

(A) Aim:Write a python programme to demonstrate the stack data structre ?

(i)push

(ii)pop

(iii)peek

(iv)display

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 22 18:46:10 2025

@author: it203

"""

class STACK:

29
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

def __init__(self):

self.l=[]

[Link]=0

def push(self):

ele = int(input("Which element do you want to insert? "))

[Link](ele)

print("Element inserted successfully\n")

def pop(self):

if len(self.l) == 0:

print("Stack is empty\n")

else:

print("The popped element is:", [Link]())

print("Element popped successfully\n")

def peek(self):

if len(self.l) == 0:

print("Stack is empty\n")

else:

print("The top element is:", self.l[-1],"\n")

def display(self):

if len(self.l) == 0:

print("Stack is empty\n")

else:

rev = self.l[::-1]

ans = " ".join(str(x) for x in rev)

print("Current stack :", ans)

obj = STACK()

while True:

30
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit")

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

if ch == 1:

[Link]()

elif ch == 2:

[Link]()

elif ch == 3:

[Link]()

elif ch == 4:

[Link]()

elif ch == 5:

print("You are Exiting....")

break

else:

print("Invalid choice. Please try again.\n")

Output:

31
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

32
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim:Write a python programme to demonstrate the queue data structre ?

(i)Enqueue

(ii)Dequeue

(iii)Dsiplay

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Apr 26 15:20:28 2025

33
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

@author: it203

"""

class Queue:

def __init__(self):

[Link]=0

self.l=[]

def enqueue(self):

[Link]=int(input("Enter element to insert:"))

[Link]([Link])

print("Element inserted Succesfully\n")

def dequeue(self):

if len(self.l)==0:

print("Queue is empty")

else:

print("the deleted element is:",[Link](0))

print("Element deleted successfully")

def display(self):

if len(self.l)==0:

print("Queue is empty")

else:

ans=" ".join(str(x) for x in self.l)

print("current Queue:",ans)

obj=Queue()

while True:

print("[Link]\[Link]\[Link]\[Link]\n")

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

34
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

if ch==1:

[Link]()

elif ch==2:

[Link]()

elif ch==3:

[Link]()

elif ch==4:

print("You are Exiting:")

break

else:

print("Invalid choice")

Output:

35
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

36
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim:Write a python programme to demonstrate the Linked List data structre ?

(i)create

(ii)insert_at_begin

(iii)insert_at_end

(iv)insert_at_spec_loc

iv)delete_at_begin

(vi)delete_at_end

(vii)delete_at_spec_loc

(viii)display

Source code:

# -*- coding: utf-8 -*-

"""

Created on Mon May 5 07:03:48 2025

@author: it203

"""

class Node:

def __init__(self, data):

[Link]=data

[Link]=None

class linked_list:

def __init__(self):

[Link]=None

[Link]=None

[Link]=None

def create(self, n):

if [Link] is None:

37
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

[Link]=n

[Link]=[Link]

else:

[Link]=n

[Link]=[Link]

def insert_at_begin(self, n):

[Link]=[Link]

[Link]=n

def insert_at_end(self, n):

if [Link]==None:

[Link]=n

else:

[Link]=[Link]

while [Link] is not None:

[Link]=[Link]

[Link]=n

def insert_at_specific(self, n, pos):

if pos<1:

print("Position should be >= 1")

return

if pos==1:

[Link]=[Link]

[Link]=n

return

tmp=[Link]

count=1

while tmp != None and count < pos -1:

38
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

tmp=[Link]

count+=1

if tmp==None:

print("Position out of range")

else:

[Link]=[Link]

[Link]=n

def delete_at_begin(self):

if [Link]==None:

print("List is empty")

else:

[Link]=[Link]

print("Deleted successfully")

def delete_at_end(self):

if [Link]==None:

print("List is empty")

elif [Link]==None:

[Link]=None

print("Deleted successfully")

else:

tmp=[Link]

while [Link] != None:

tmp = [Link]

[Link] = None

print("Deleted successfully")

def delete_at_specific(self, pos):

if [Link]==None:

39
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("List is empty")

return

if pos<1:

print("Position should be >= 1")

return

if pos==1:

[Link]=[Link]

print("Deleted successfully")

return

tmp=[Link]

count=1

while tmp != None and count < pos -1:

tmp=[Link]

count+=1

if tmp is None or [Link] is None:

print("Position out of range")

else:

[Link]=[Link]

print("Deleted successfully")

def display(self):

if [Link]==None:

print("List is empty")

return

tmp=[Link]

while tmp is not None:

print([Link], "->", end=" ")

tmp=[Link]

40
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("None")

a=linked_list()

while True:

print("\n1. Create\n2. Insert at Begin\n3. Insert at


End\n4.insert_at_specific\n5.Delete_at_begin\n6.delete_at_end\n7.
Delete_at_specific\[Link]\n9. Exit")

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

if ch==1:

d=int(input("Enter the data: "))

n=Node(d)

[Link](n)

elif ch==2:

d=int(input("Enter the data: "))

n=Node(d)

a.insert_at_begin(n)

elif ch==3:

d=int(input("Enter the data: "))

n=Node(d)

a.insert_at_end(n)

elif ch==4:

d=int(input("Enter the data: "))

pos=int(input("Enter the position: "))

n=Node(d)

a.insert_at_specific(n, pos)

elif ch==5:

a.delete_at_begin()

elif ch==6:

a.delete_at_end()

41
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

elif ch==7:

pos=int(input("Enter the position: "))

a.delete_at_specific(pos)

elif ch==8:

[Link]()

elif ch==9:

break

else:

print("Invalid choice!")

Output:

42
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

43
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

44
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

45
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

(A) Aim:Write a python programme to demonstrate the multiple inheritance ?


Create a calculator with the following functions ?
(i)General cal
(ii)Scientific cal
(ii)Advanced Scientific cal

Source code:

import math

class GC:

def __init__(self):

self.a = 0

self.b = 0

def read1(self):

self.a = int(input("Enter the value of a: "))

self.b = int(input("Enter the value of b: "))

def add(self):

print("The Addition is",self.a + self.b)

def sub(self):

46
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("The Subtraction is", self.a - self.b)

def mul(self):

print("The Multiplication is", self.a * self.b)

def div(self):

if self.b!= 0:

print("The Division is", self.a / self.b)

else:

print("Division by zero is not allowed.")

class SC(GC):

def lcm(self):

greater = max(self.a, self.b)

while True:

if greater % self.a == 0 and greater % self.b == 0:

print("The LCM of a and b is:", greater)

break

greater += 1

def gcd(self):

while self.b:

self.a, self.b = self.b, self.a % self.b

print("GCD is:", self.a)

def fact(self):

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

if n < 0:

print("Factorial not defined for negative numbers.")

elif n==0:

print("1")

else:

47
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

f=1

for i in range(1,n+1):

f*=i

print("the factorial of a given number is",f)

def sqrt(self):

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

result= n ** 2

print("The square root is:",result)

class ASC(SC):

def cos(self):

x = float(input("Enter angle in degrees: "))

print("Cosine is:", [Link]([Link](x)))

def sin(self):

x = float(input("Enter angle in degrees: "))

print("Sine is:", [Link]([Link](x)))

def tan(self):

x = float(input("Enter angle in degrees: "))

print("Tangent is:", [Link]([Link](x)))

def log(self):

x = float(input("Enter a number: "))

if x > 0:

print("Logarithm is:", [Link](x))

else:

print("Logarithm not defined for non-positive numbers.")

def fa_to_cel(self):

f=int(input("enter fahrenheat value"))

c=(f-32)*5/9

48
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("fahrenheat to celsius value is: ",c)

def cel_to_fa(self):

c=int(input("enter celsius value"))

f=(c*9/5)+32

print("celsius to fahrenheat to celsius value is: ",f)

def gram_to_kg(self):

gram=int(input("enter gram value"))

kg=gram/1000

print("gram to kilogram conversion is: ",kg)

def kg_to_gram(self):

kg=int(input("enter kg value"))

gram=kg*1000

print("kg to gram conversion is: ",gram)

def dollar_to_rupees(self):

d=int(input("enter dollar value"))

r=d*85

print("dollar to rupees conversion is: ",r)

def rupees_to_dollar(self):

r=int(input("enter rupees value"))

d=r/85

print("rupees to dollar conversion is: ",d)

while True:

print("\n1. General Calculator\n2. Scientific Calculator\n3. Advanced Scientific


Calculator\n4. Exit")

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

if ch == 1:

obj1 = GC()

49
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division")

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

if ch1 == 1:

obj1.read1()

[Link]()

elif ch1 == 2:

obj1.read1()

[Link]()

elif ch1 == 3:

obj1.read1()

[Link]()

elif ch1 == 4:

obj1.read1()

[Link]()

elif ch == 2:

obj2 = SC()

print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. LCM\n6.


GCD\n7. Factorial\n8. Square Root")

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

if ch2==1:

obj2.read1()

[Link]()

elif ch2==2:

obj2.read1()

[Link]()

elif ch2==3:

obj2.read1()

50
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

[Link]()

elif ch2==4:

obj2.read1()

[Link]()

elif ch2 == 5:

obj2.read1()

[Link]()

elif ch2 == 6:

obj2.read1()

[Link]()

elif ch2 == 7:

[Link]()

elif ch2 == 8:

[Link]()

elif ch == 3:

obj3 = ASC()

print("[Link]\[Link]\[Link]\[Link]\[Link]\[Link]\[Link]
\[Link] root\[Link] functions\[Link] Conversions\n")

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

if ch3 == 1:

obj3.read1()

[Link]()

elif ch3 == 2:

obj3.read1()

[Link]()

elif ch3 == 3:

obj3.read1()

51
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

[Link]()

elif ch3 == 4:

obj3.read1()

[Link]()

elif ch3== 5:

obj3.read1()

[Link]()

elif ch3==6:

obj3.read1()

[Link]()

elif ch3==7:

obj3.read1()

[Link]()

elif ch3==8:

obj3.read1()

[Link]()

elif ch3==9:

print("[Link]\[Link]\[Link]\[Link]")

ch33=int(input("enter your choice"))

if ch33==1:

[Link]()

elif ch33==2:

[Link]()

elif ch33==3:

[Link]()

elif ch33==4:

[Link]()

52
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

elif ch3==10:

print("[Link] to celsius\[Link] to fahrenheat\[Link] to


kilograms\[Link] to grams\[Link] to rupees\[Link] to dollar\n")

ch44=int(input("enter your choice"))

if ch44==1:

obj3.fa_to_cel()

elif ch44==2:

obj3.cel_to_fa()

elif ch44==3:

obj3.gram_to_kg()

elif ch44==4:

obj3.kg_to_gram()

elif ch44==5:

obj3.dollar_to_rupees()

elif ch44==6:

obj3.rupees_to_dollar()

elif ch==4:

print("Exiting Calculator.")

break

else:

print("Invalid Choice. Try again.")

Output:

53
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

54
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

55
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

56
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

57
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Write a python programme on creation of EMPLOYEE DATABASE and perform


these operations ?

(a)Create

(b)Insert

(c)Display

(d)Update

(e)Search

(f)Delete

(g)Exit

Source code:

# -*- coding: utf-8 -*-

"""

Created on Tue Jun 10 08:26:47 2025

@author: it203

"""

class DATABASE:

def create(self):

import sqlite3

try:

conn = [Link]("[Link]")

cursor = [Link]()

print("succesfully connected to sqlit3")

myquery = """

CREATE TABLE EMP (

EMPNAME TEXT,

EMPID INTEGER,

58
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

DNO INTEGER,

GENDER TEXT,

EMPSALARY INTEGER

"""

[Link](myquery)

print("SQLite table created successfully.")

[Link]()

except [Link] as error:

print("ERROR,while creating sqlite3 database file")

finally:

if conn:

[Link]()

print("SQLite connection closed.")

def insert(self):

import sqlite3

try:

conn=[Link]("[Link]")

cursor=[Link]()

print("Successfully connected to SQLite Database")

n=int(input("Enter the number of records you want to insert: "))

for i in range(n):

print("Enter employee {} data".format(i+1))

empname=input("Enter the empname: ")

empid=int(input("Enter the employee id: "))

dno=int(input("Enter the dno: "))

gender=input("Enter the Gender: ")

59
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

salary=int(input("Enter the salary: "))

[Link](("INSERT INTO EMP(EMPNAME, EMPID, DNO, GENDER,


EMPSALARY) VALUES (?, ?, ?, ?, ?)"),(empname,empid,dno,gender,salary))

[Link]()

print("Values are inserted successfully!")

except [Link] as error:

print("Failed to insert data into EMP table:", error)

finally:

if conn:

[Link]()

print("SQLite connection is closed.")

def display(self):

import sqlite3

try:

conn=[Link]("[Link]")

cursor=[Link]()

print("Data base connected to sqlite!")

cr="""SELECT * FROM EMP"""

[Link](cr)

records=[Link]()

print("Employee details are..")

for row in records:

print("name is:",row[0])

print("Id is:",row[1])

print("Dno is:",row[2])

print("Gender is:",row[3])

60
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Salary is:",row[4])

print("\n")

except [Link] as error:

print("Failed to insert data into EMP table:", error)

finally:

if conn:

[Link]()

print("SQLite connection is closed.")

def update(self):

import sqlite3

try:

conn = [Link]("[Link]")

cursor = [Link]()

print("Database connected to SQLite!")

empid = int(input("Enter the employee ID you want to update: "))

[Link]("SELECT * FROM EMP WHERE EMPID = ?", (empid,))

record = [Link]()

if record:

print("Employee found: ")

new_name = input("Enter the new employee name: ")

cr = """UPDATE EMP SET EMPNAME = ? WHERE EMPID = ?"""

[Link](cr, (new_name, empid))

[Link]()

print("Employee data updated successfully.")

else:

print("No employee found")

except [Link] as error:

61
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print("Failed to update data in EMP table:", error)

finally:

if conn:

[Link]()

print("SQLite connection is closed.")

def search(self):

import sqlite3

try:

conn = [Link]("[Link]")

cursor = [Link]()

print("Database connected to SQLite!")

empid = int(input("Enter the employee ID to search: "))

[Link]("SELECT * FROM EMP WHERE EMPID = ?", (empid,))

records=[Link]()

if records:

print("Employee found")

for row in records:

print("name is:",row[0])

print("Id is:",row[1])

print("Dno is:",row[2])

print("Gender is:",row[3])

print("Salary is:",row[4])

print("\n")

else:

print("No employee found")

except [Link] as error:

print("Failed to search data in EMP table:", error)

62
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

finally:

if conn:

[Link]()

print("SQLite connection is closed.")

def delete(self):

import sqlite3

try:

conn = [Link]("[Link]")

cursor = [Link]()

print("Database connected to SQLite!")

empid = int(input("Enter the employee ID to delete: "))

[Link]("DELETE FROM EMP WHERE EMPID = ?", (empid,))

[Link]()

print("Employee data deleted successfully.")

except [Link] as error:

print("Failed to delete data from EMP table:", error)

finally:

if conn:

[Link]()

print("SQLite connection is closed.")

obj=DATABASE()

while True:

print("\[Link] table\[Link] data \[Link] data\[Link] data \[Link]


data\[Link] data\[Link]")

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

if choice == 1:

[Link]()

63
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

elif choice == 2:

[Link]()

elif choice == 3:

[Link]()

elif choice == 4:

[Link]()

elif choice == 5:

[Link]()

elif choice == 6:

[Link]()

elif choice == 7:

print("Exiting. Thank you for using database!")

break

else:

print("Invalid choice. Please try again..")

64
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

65
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

66
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

67
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Write a python programme to demonstrate the EXCEL- file on student management
system ?

(a)Basic

(b)Range

(c)Merge

(d)Sort

(e)Search

(f)Startswith

(g)Exit

Source code:

# -*- coding: utf-8 -*-

"""

Created on Fri Jun 13 10:02:01 2025

@author: ambat

"""

class EXCEL:

def basic(self):

import pandas as pd

df = pd.read_excel('[Link]')

print("sum:", df["marks"].sum())

print("mean:", df["marks"].mean())

print("max:", df["marks"].max())

print("min:", df["marks"].min())

def range(self):

import pandas as pd

68
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

df = pd.read_excel('[Link]')

def find(start_range, end_range):

return df[(df['marks'] >= start_range) & (df['marks'] <= end_range)]

start_range = 20

end_range = 30

students_in_range = find(start_range, end_range)

print(students_in_range)

def merge(self):

import pandas as pd

df1 = pd.read_excel('[Link]', sheet_name=0)

df2 = pd.read_excel('[Link]', sheet_name=1)

df3 = [Link]([df1, df2], ignore_index=True)

df3.to_excel("[Link]", index=False)

print("Sheets merged and saved to [Link]")

def sort(self):

import pandas as pd

df = pd.read_excel('[Link]')

sorted_df = df.sort_values(['marks'], ascending=False)

print(sorted_df)

def search(self):

import pandas as pd

df = pd.read_excel('[Link]')

def find_student_details(regno):

return df[df['regno'] == regno]

regno = ['Y23AIT901']

for reg in regno:

print(find_student_details(reg))

69
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

print()

def startswith(self):

import pandas as pd

df = pd.read_excel('[Link]')

filtered = df[df['name'].[Link]('s', na=False)]

print("Students whose names start with 's':")

print(filtered)

print("\n")

obj = EXCEL()

while True:

print("[Link] Statistics\[Link] of Marks\[Link] sheets\[Link] by Marks\[Link]


by [Link]\[Link] with letter\[Link]\n")

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

if n == 1:

[Link]()

elif n == 2:

[Link]()

elif n == 3:

[Link]()

elif n == 4:

[Link]()

elif n == 5:

[Link]()

elif n == 6:

[Link]()

elif n == 7:

print("Exiting program.")

70
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

break

else:

print("Enter a valid choice.")

Output:

71
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

72
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

73
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

74
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Python Program to implement a Simple Game. (Tic Tac Toe or Number Game or Quiz
or Puzzle or Etc...)

Source code:

# -*- coding: utf-8 -*-

"""

Created on Sat Jun 21 11:25:26 2025

@author: ambat

"""

words = ["elephant", "tiger", "giraffe", "monkey", "parrot"]

puzzles = ["e _ e _ _ a _ _", "t _ _ e _", "g _ _ _ _ f _", "m _ _ _ e _", "p _ _ _ _ t"]

print("Welcome to the Word Puzzle Game!")

print("You will be shown 5 puzzles. Try to guess the full word.\n")

while True:

score = 0

for i in range(len(words)):

print("Puzzle", i + 1)

print("Clue:", puzzles[i])

user_input = input("Your guess: ")

if user_input.lower() == words[i]:

print("Correct! Well done.\n")

score = score + 1

else:

print("Wrong. The correct answer was:", words[i], "\n")

print("Game Over.")

print("Your score is", score, "out of", len(words))

choice = input("Do you want to play again? (yes/no): ")

75
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

if [Link]() != "yes":

print("Thank you for playing!")

break

print()

Output:

76
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

77
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

78
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

Aim: Python program to implement a simple calculator with a GUI interface using the tkinter
module.

Source code:

# -*- coding: utf-8 -*-

"""

Created on Fri Jun 21 12:02:01 2025

@author: ambat

"""

import tkinter as tk

def calculate():

num1 = [Link]()

num2 = [Link]()

op = [Link]()

try:

n1 = float(num1)

n2 = float(num2)

if op == "+":

result = n1 + n2

elif op == "-":

result = n1 - n2

elif op == "*":

result = n1 * n2

elif op == "/":

if n2 != 0:

result = n1 / n2

else:

79
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

result_label.config(text="Cannot divide by zero")

return

else:

result_label.config(text="Select a valid operator")

return

result_label.config(text="Result: " + str(result))

except ValueError:

result_label.config(text="Enter valid numbers")

window = [Link]()

[Link]("Simple Calculator")

label1 = [Link](window, text="Enter first number:")

[Link]()

entry1 = [Link](window)

[Link]()

label2 = [Link](window, text="Enter second number:")

[Link]()

entry2 = [Link](window)

[Link]()

label3 = [Link](window, text="Choose an operator:")

[Link]()

operator = [Link]()

[Link]("+")

dropdown = [Link](window, operator, "+", "-", "*", "/")

[Link]()

button = [Link](window, text="Calculate", command=calculate)

[Link]()

result_label = [Link](window, text="Result:")

80
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

result_label.pack()

[Link]()

Output:

81
DEPARTMENT OF INFORMATION TECHNOLOGY
PYTHON PROGRAMMING LAB (20ITL401/SOC2) REGDNO: Y23AIT403

82
DEPARTMENT OF INFORMATION TECHNOLOGY

You might also like