Experiment: .
# Creating a menu driven program to perform Arithmetic operation
Aim:
To write a menu driven python to perform arithmetic operation (+,-,*, /) based
on the users choice.
Source code:
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
opt=int(input("Enter your choice:"))
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if opt==1:
c=a+b
print("The Addition of two number is:",c)
elif opt==2:
c=a-b
print("The Subtraction of two number is:",c)
elif opt==3:
c=a*b
print("The Multiplication of two number is:",c)
elif opt==4:
if b==0:
print("Enter any other number other than 0")
else:
c=a/b
print("The Division of two number is:",c)
else:
print("Invalid option")
Result:
Thus, the above python program is executed successfully and the output is verified.
Sample output:
Experiment: .2
# Creating a python program to display Fibonacci series
Aim:
To write a python progam to display Fibonnaci series up to ‘n’ number.
Source code:
First=0
Second=1
no=int(input("How mant Fibonaccinumbers you want to display?"))
if no<=0:
print("Please enter Positive integer")
else:
print(First)
print(Second)
for i in range(25,no):
Third=First+Second
First=Second
Second=Third
print(Third)
Result:
Thus,the above python program is executed successfully and the output is verified.
Sample output:
Experiment:.3
# Creating a menu driven python to find factorial and sum of list of
number using function
Aim:
To write a menu driven program to find factorial and sum of list of number using
function.
Source code:
def factorial(n):
if n < 0:
return "Factorial does not exist for negative numbers."
elif n == 0 or n == 1:
return 1
else:
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
# Main program:
print("1. Find Factorial")
print("2. Find Sum of List of Numbers")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
num = int(input("Enter a number to find its factorial: "))
print(f"Factorial of {num} is: {factorial(num)}")
elif choice == '2’
nums = input("Enter numbers separated by spaces: ")
num_list = [int(x) for x in [Link]()]
print(f"Sum of numbers {num_list} is: {sum_of_list(num_list)}")
elif choice == '3':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a valid option.")
Result:
Thus, the above python program is executed successfully and the output is verified.
Sample output:
Experiment: .4
# Creating a python program to implement mathematical function
Aim:
To write a python program to implement mathematical Function to find:
[Link] find square of a number
[Link] find log of a number(i.e.Log10)
[Link] find quad of a number
Source code:
import math
def square(num):
return num ** 2
def log_base10(num):
if num <= 0:
return "Logarithm not defined for zero or negative numbers."
return math.log10(num)
def quad(num):
return num ** 4
number = float(input("Enter a number: "))
print(f"Square of {number} = {square(number)}")
print(f"Log10 of {number} = {log_base10(number)}")
print(f"Quad (4th power) of {number} = {quad(number)}")
Result:
Thus, the above python program is executed successfully and the output is verified
Source output:
Experiment: .5
# Creating a python program to generate Random between 1 to 6
Aim:.
To write a python program to generate random number 1 to 6 stimulate dice.
Source code:.
import random
while True:
choice = input("\nDo you want to roll the dice (y/n): ")
if [Link]() == 'y':
no = [Link](1, 6)
print("\nYour number is:", no)
else:
print("\nExiting... Goodbye!")
break
Result:
Thus, the above python program is executed successfully and the output is verified.
Sample output:
Experiment: .6
# Creating a python program to read a text file line by line and display
each word separated by ‘B’
Aim:
To write a python program to read a text file “[Link]” line by line and display each
word separated by ‘#’.
Source code:
f = open("[Link]", "r")
for line in f:
for word in [Link]():
print(word + "#", end=" ")
print()
[Link]()
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
[Link]:
Python program executed output:
Experiment: .7
# Creating a python program to read a text file and display the number of
vowels/consonants/Lower case/Upper case characters
Aim:
To write a python program to read a text file “[Link]” and display the number of
vowels/consonant/Lowf=open("[Link]",'r')
Source code:
contents=[Link]()
vowels=0
consonant=0
lower_case=0
upper_case=0
for ch in contents:
if ch in 'AEIOU':
Vowels=vowels+1
if ch in 'bcdfghklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ':
consonant=consonant+1
if [Link]():
lower_case=lower_case+1
if [Link]():
upper_case=upper_case+1
[Link]()
print("the total numbers of vowels in the file:",vowels)
print("the total numbers of consonant in the file:",consonant)
print("the total numbers if uppercase in the file:",upper_case)
print("the total numbers of lowercase in the file:",lower_case)
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
[Link]:
Python program Executed Output:
Experiment: .8
# Creating a python program to copy particular lines of Text file into
an another Text file
Aim:
To write a python program to read lines from a text file “[Link]” and copy
those lines into another file which are starting with an alphabet ‘a’ or ‘A’.
Source code:
F1=open("[Link]",'r')
F2=open("[Link]",'w')
while True:
line=[Link]()
if line=='':
break
if line[0]=='a' or line[0]=='A':
[Link](line)
print("All lines which are starting with character 'a' or 'A' has been copied
successfully into [Link]")
[Link]()
[Link]()
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
[Link]:
Python Executed program output:
[Link]:
Experiment: .9
# Creating a python program to create and search records in binary file
Aim:
To write a python program to create a binary file with roll number and name. Search
for a given roll number and display the name, if not found display appropriate
message.
Sample code:
import pickle
def Create():
f = open("[Link]", 'ab')
opt = 'y'
while [Link]() == 'y':
Roll_No = int(input('Enter roll number: '))
Name = input("Enter Name: ")
L = [Roll_No, Name]
[Link](L, f)
opt = input("Do you want to add another student detail (y/n): ")
[Link]()
def Search():
f = open("[Link]", 'rb') # same filename as in Create()
no = int(input("Enter [Link] of student to search: "))
found = 0
try:
while True:
S = [Link](f)
if S[0] == no:
print("The searched [Link] is found and details are:", S)
found = 1
break
except EOFError:
pass # reached end of file
[Link]()
if found == 0:
print("The searched [Link] is not found")
# Main Program
Create()
Search()
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
Experiment: .10
# Creating a python program to create and Update/Modify records in
binary file
Aim:
To write a python program to create a binary file with roll number, name, mark
and update/modify the mark for a given number.
Source code:
import pickle
import os
def Create():
with open("[Link]", 'ab') as F:
opt = 'y'
while [Link]() == 'y':
Roll_No = int(input('Enter roll number: '))
Name = input("Enter Name: ")
Mark = int(input("Enter Marks: "))
L = [Roll_No, Name, Mark]
[Link](L, F)
opt = input("Do you want to add another student detail (y/n): ")
print("Student details saved successfully.\n")
def Update():
if not [Link]("[Link]"):
print("File not found! Create records first.\n")
return
records = []
found = False
with open("[Link]", 'rb') as F:
while True:
try:
[Link]([Link](F))
except EOFError:
break
no = int(input("Enter Student [Link] to modify marks: "))
for rec in records:
if rec[0] == no:
print("Record found:", rec)
rec[2] = int(input("Enter new marks to be updated: "))
found = True
print("Marks updated successfully:", rec)
break
if not found:
print("The searched [Link] is not found.\n")
else:
with open("[Link]", 'wb') as F:
for rec in records:
[Link](rec, F)
print("File updated successfully.\n")
#Main program
Create()
Update()
Result:
Thus, the above python program is executed successfully and the output is verified.
Sample output:
Experiment: .11
# Creating a python program to create and search Employee`s record is
CSV File
Aim:
To write a python program create a CSV file to store Empno, Name, Salary and search
any Empho and display Name, Salary and if not found display appropriate message.
Source code:
import csv
def Create():
F = open("[Link]", 'a', newline='')
W = [Link](F)
opt = 'y'
while [Link]() == 'y':
No = int(input("Enter Employee Number: "))
Name = input("Enter Employee Name: ")
Sal = float(input("Enter Employee Salary: "))
L = [No, Name, Sal]
[Link](L)
opt = input("Do you want to continue (y/n)?: ")
[Link]()
def Search():
F = open("[Link]", 'r', newline='')
no = int(input("Enter Employee number to search: "))
found = 0
R = [Link](F)
for data in R:
if data[0] == str(no):
print("\nEmployee Details are:")
print("=================")
print("Employee No.:", data[0])
print("Name:", data[1])
print("Salary:", data[2])
print("=================")
found = 1
break
if found == 0:
print("The searched Employee number is not found.")
[Link]()
# Main program
Create()
Search()
Result:
Thus, the above python program is executed successfully and the output is verified.
Sample output:
Experiment: .12
# Creating a python program to implement Stack operation
Aim:
To write a pytḥon program to implement Stack using a list data structure.
Source code:
def PUSH():
ele=int(input("Enter the element which you wantto push:"))
[Link](ele)
def POP():
if Stack==[]:
print("Stack is Empty/Underflow")
else:
print("The deleted element is:",[Link]())
def PEEK():
top=len(Stack)-1
print("The top most element of stack is:",Stack[top])
def Disp():
top=len(Stack)-1
print("The Stack element are:")
for i in range(top,-1,-1):
print(Stack[i])
#Main program
Stack=[]
opt='y'
while opt=='y'or opt=='Y':
print("Stack Operations")
print("****************")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
print("****************")
opt=int(input("Enter your choice:"))
if opt==1:
PUSH()
elif opt==2:
POP()
elif opt==3:
PEEK()
elif opt==4:
Disp()
else:
print("Invalid Input")
opt=input("Do you want to perform another stack operation(y/n)?:")
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
Experiment: .13
# Creating a python program to integrate MYSQL with python
(Inserting records and displaying records)
Aim:
To write a python program to integrate MYSQL with python by inserting
Emp table and display the records.
Source code:
import [Link]
con=[Link](host='localhost',username='root',database='empoyees')
if con.is_connected():
cur=[Link]()
opt='y'
while opt=='y':
No=int(input("Enter Employee Number:"))
Name=input("Enter Empoyee Name:")
Gender=input("Enter Employee Gendr(M/F):")
Salary=int(input("Enter Employee Salary:"))
Query="INSERT INTO EMP VALUES({},'{}','{}',{})".format(No,Name,Gender,Salary)
[Link](Query)
[Link]()
print("Record stored Successfully")
opt=input("Do you want to add another employee details(y/n):")
Query="SELECT*FROM EMP";
[Link](Query)
data=[Link]()
for i in data:
print(i)
[Link]()
Result:
Thus, the python program is executed successfully and output is verified.
Sample output:
Python Executed Program Output:
SQL OUTPUT:
Experiment: .14
# Creating a python program to integrate MYSQL with python
(Searching and displaying Records)
Aim:
To write a python program to integrate MYSQL with python to search an Employee
using EMPID and the record if present in already existing table EMP, if not display
the appropriate message.
Source code:
import [Link]
con=[Link](host='localhost',username='root',database='empoyees')
if con.is_connected():
cur=[Link]()
print("*********************************")
print("Welcome to Employee Search Screen")
print("*********************************")
No=int(input("Enter the Employee number to search"))
Query="SELECT*FROM EMP WHERE EMID={}".format(No)
[Link](Query)
data=[Link]()
if data!=None:
print(data)
else:
print("Record not found")
[Link]()
Result:
Thus, the python program is executed successfully and output is verified.
Sample output:
Python Executed program output:
RUN-1
RUN-2
SQL OUTPUT:
OUTPUT-1:
Ouput-2:
Experiment: .15
# Creating a python program to integrate MYSQL with python
(Updating RECORDS)
Aim:
To write a python program to integrate MYSQL with python to search an
Employee using EMPID and update the salary of an employee if present in already
existing table EMP, if not display the appropriate message.
Source code:
import [Link]
con=[Link](host='localhost',username='root',database='empoyees')
if con.is_connected():
cur=[Link]()
print("*********************************")
print("Welcome to Employee Search Screen")
print("*********************************")
No=int(input("Enter the Employee number to search"))
Query="SELECT*FROM EMP WHERE EMID={}".format(No)
[Link](Query)
data=[Link]()
if data!=None:
print("Record found details are:")
print(data)
ans=input("Do you want to update the salary of the above employee(y/n)?:")
if ans=='y'or'Y':
New_Sal=int(input("Enter the New Salary of an Employee:"))
Q1="UPDATE EMP SET SALARY={} WHERE EMPID={}".format(New_Sal, No)
[Link](Q1)
[Link]()
print("Employee Salary Updated Successfully")
Q2="SELECT*FROM EMP"
[Link](Q2)
data=[Link]()
for i in data:
print(i)
else:
print("Record not found!!!")
Result:
Thus, the above python program is executed successfully and output is verified.
Sample output:
RUN-1:
RUN-2:
SQL OUTPUT:
Experiment: .16
(SQL COMMANDS EXERCISE-1)
Aim:
To write Queries for the following Question based on the given table:
Rollno Name Gender Age Dept DOA Fees
1 Arun M 24 COMPUTER 1997-01-10 120
2 Ankit M 21 HISTORY 1998-03-24 200
3 Anu F 20 HINDI 1996-12-12 300
4 Bala M 19 NULL 1997-07-01 400
5 Charan M 18 HINDI 1997-09-05 250
6 Deepa F 19 HISTORY 1997-06-27 300
7 Dinesh M 22 COMPUTER 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200
(a) Write a Query to new database in the name of “STUDENTS”
Sol:mysql>Create DATABASE STUDENTS;
(b) Write a Query to open the database “STUDENTS”
Sol:mysql> Use STUDENTS:
(c) Write a Query to create the above table called: Info
Sol:
Mysql> CREATE TABLE STU(Rollno int primary key, Name varchar(10), Gender
varchar(3), Age int,Dept varchar(15), DOA data, Fees int);
(d) Write a Query to list all the existing database names.
Sol:
mysql>SHOW DATABASES;
Output:
(e) Write a Query to list all the tables that exist in the Current database.
Sol:
mysql> SHOW TABLES;
Output:
(f) Write a Query to insert all the rows of above table into info table.
Sol:
(g) Write a Query to display all the details of the Employee from the above table‘STU`.
Sol:
mysql>Select*FROM STU;
Output:
(h) Write a query to Rollno, Name and Department of the student from STU table.
Sol:
mysql> Select ROLLNO,NAME,DEPT FROM STU;
Output: