Q.1 WAP to calculate compound simple interest after taking the principle, rate and time.
Ans:
Q.1 WAP to print the number of occurrences of a substring into a line. Ans:
WAP to check the given string is palindrome or not. Ans:
Q.2 WAP that:
o Prompt the user for a string
o Extract all the digits from the string.
o If there are digits
Sum the collected digits together.
Printout:
The original string
The digits
The sum of the digits
o If there are no digits
Print the original string
A message “Has no Digits”
Ans:
Q.1 WAP that repeatedly asks the user to enter product names and prices. Store all of them in a dictionary whose
keys are product names and values are prices. And also write a code to search an item from the dictionary.
Ans:
Q.2 WAP to create a dictionary named year whose keys are month names and values are their corresponding number
of days.
Ans:
Q.3 WAP that repeatedly asks the user to enter product names and prices. Store all of them in a
dictionary whose keys are product names and values are prices. And also write a code to search an
item from the dictionary.
:
print("-----Program for Student Information-----")
D = dict()
n = int(input('How many student record you want to store?? '))
# Add student information
# to the dictionary
for i in range(0,n):
x, y = input("Enter the complete name (First and last name) of student: ").split()
z = input("Enter contact number: ")
m = input('Enter Marks: ')
D[x, y] = (z, m)
# define a function for sorting
# names based on first name
def sort():
ls = list()
# fetch key and value using
# items() method
for sname,details in D.items():
# store key parts as an tuple
tup = (sname[0],sname[1])
# add tuple to the list
ls.append(tup)
# sort the final list of tuples
ls = sorted(ls)
for i in ls:
# print first name and second name
print(i[0],i[1])
return
# define a function for
# finding the minimum marks
# in stored data
def minmarks():
ls = list()
# fetch key and value using
# items() methods
for sname,details in D.items():
# add details second element
# (marks) to the list
ls.append(details[1])
# sort the list elements
ls = sorted(ls)
print("Minimum marks: ", min(ls))
return
# define a function for searching
# student contact number
def searchdetail(fname):
ls = list()
for sname,details in D.items():
tup=(sname,details)
ls.append(tup)
for i in ls:
if i[0][0] == fname:
print(i[1][0])
return
# define a function for
# asking the options
def option():
choice = int(input('Enter the operation detail: \n \
1: Sorting using first name \n \
2: Finding Minimum marks \n \
3: Search contact number using first name: \n \
4: Exit\n \
Option: '))
if choice == 1:
# function call
sort()
print('Want to perform some other operation??? Y or N: ')
inp = input()
if inp == 'Y':
option()
# exit function call
exit()
elif choice == 2:
minmarks()
print('Want to perform some other operation??? Y or N: ')
inp = input()
if inp == 'Y':
option()
exit()
elif choice == 3:
first = input('Enter first name of student: ')
searchdetail(first)
print('Want to perform some other operation??? Y or N: ')
inp = input()
if inp == 'Y':
option()
exit()
else:
print('Thanks for executing me!!!!')
exit()
option()
The question is, write a Python program to search a given element from a given
list. The program given below is answer to this question:
mylist = []
print("Enter 5 elements for the list: ")
for i in range(5):
val = int(input())
mylist.append(val)
print("Enter an element to be search: ")
elem = int(input())
for i in range(5):
if elem == mylist[i]:
print("\nElement found at Index:", i)
print("Element found at Position:", i+1)
or
print("Enter the size of list: ", end="")
tot = int(input())
print("Enter", tot, "elements: ", end="")
x = []
for i in range(tot):
x.append(input())
print("\nThe list is:")
print(x)
print("\nEnter an element to search: ", end="")
element = input()
if element in x:
print("\nIt is available in the list")
else:
print("\nIt is not available in the list")
Binary search
# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# If x is greater, ignore left half
if arr[mid] < x:
low = mid + 1
# If x is smaller, ignore right half
elif arr[mid] > x:
high = mid - 1
# means x is present at mid
else:
return mid
# If we reach here, then the element was not present
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Bubble sort
def bubblesort(elements):
swapped = False
# Looping from size of array from last index[-1] to index [0]
for n in range(len(elements)-1, 0, -1):
for i in range(n):
if elements[i] > elements[i + 1]:
swapped = True
# swapping data if the element is less than next element in the array
elements[i], elements[i + 1] = elements[i + 1], elements[i]
if not swapped:
# exiting the function if we didn't make a single swap
# meaning that the array is already sorted.
return
elements = [39, 12, 18, 85, 72, 10, 2, 18]
print("Unsorted list is,")
print(elements)
bubblesort(elements)
print("Sorted Array is, ")
print(elements)
# Python program for implementation of Insertion Sort
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
#sorting the array [12, 11, 13, 5, 6] using insertionSort
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
lst = [] #empty list to store sorted elements
print("Sorted array is : ")
for i in range(len(arr)):
lst.append(arr[i]) #appending the elements in sorted order
print(lst)
# Selection sort in Python
# time complexity O(n*n)
#sorting by finding min_index
def selectionSort(array, size):
for ind in range(size):
min_index = ind
for j in range(ind + 1, size):
# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])
arr = [-2, 45, 0, 11, -9,88,-97,-202,747]
size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
Data File Handling
1- Program to write records in a text file
2- Program to read text file for the following
(a) To count the no of alphabets ‘A’ and ‘M’
(b) To count all vowels & consonants separately
(c) To count all uppercase and lowercase letters
(d) To count total no of words
(e) To count no of words ‘Me’ or ‘My ‘
(f) To count the words starting with ‘T’ or ‘t’
(g) To replace all words ‘Me’ with ‘you’ and store in a new text file
# Read in the file
with open('myfile.txt', 'r') as file :
filedata = file.read()
# Replace the target string
if 'are' in filedata:
filedata = filedata.replace('are', 'is')
# Write the file out again
with open('myfile1.txt', 'w') as file:
file.write(filedata)
print(filedata)
(h) To read lines and count the no of lines
(i) To count the no of lines starting with alphabet ‘M’ or ‘T’
3- Program for Binary file for the following:
(a) Write records using list / dictionary
(b) Read & show all records
(c) Read & show specific record (as per search key)
(d) To update records
(e) To delete records
(f) To backup records
4- Program for CSV file :
(a) Write records
(b) To read and show all
(c) To read and show specific record (as per search key)
Data structure
Stacks
1- Push / POP / Display (traverse) using list
2- Push / POP / Display (traverse) using dictionary
My Sql
1- Command for creating database and checking it
a) Create a database db22boards
create database db22boards
b) Use the database db22boards
use db22boards
c) Check the current selected database
database()
d) To list all databases
show databases
e) To list all tables in active database
Show tables
2. Command for creating a table.
3. Command for showing the structure of table.
4. Command to show tables present in database.
5. Command for inserting data into a table.
6. Command to view the contents of the table.
7. Command to retrieve data.
8. Command for using keyword DISTINCT.
9. Command for using WHERE clause.
10. Command for using ORDER BY clause.
11. Command for using UPDATE .
12. Command for using ALTER (to modify structure of table).
13. Command for using LIKE operator.
14. Command for using aggregate functions.
15. Command for using GROUP BY.
16. Command for using HAVING clause.
17. Command for using Group by with order by.
18. Command for using group by and having clause with where clause.
19. Command for equi-join of tables.
20. Command to retrieve data from two tables.
21. Command for using group by clause in join.
22. Command for using group by and order by clause in equi-join.
23. Command for using where clause and group by.
24. Command for adding primary key.
25. Command to delete a column.
26. Command to remove primary key.
27. Command to increase marks.
28. Command to change data type of an existing column.
29. Command to a delete table.
A department is considering to maintain their worker data using SQL to store the data. As a database
administer, Karan has decided that :
Name of the database - Department Name of the table - WORKER
The attributes of WORKER are as follows: WORKER_ID - character of size 3 FIRST_NAME – character of size
10 LAST_NAME– character of size 10 SALARY – numeric JOINING_DATE – Date DEPARTMENT – character
of size 10
WORKER_I D FIRST_NA ME LAST_NAM E SALARY JOINING_D ATE DEPARTM
ENT
001 Monika Arora 100000 2014-02-20 HR
002 Niharika Diwan 80000 2014-06-11 Admin
003 Vishal Singhal 300000 2014-02-20 HR
004 Amitabh Singh 500000 2014-02-20 Admin
005 Vivek Bhati 500000 2014-06-11 Admin
06 Vipul Diwan 200000 2014-06-11 Account
07 Satish Kumar 75000 2014-02-20 Account
08 Monika Chauhan 80000 2014-04-11 Admin
a) Write a query to create the given table WORKER.
b) Identify the attribute best suitable to be declared as a primary key.
c) Karan wants to increase the size of the FIRST_NAME column from
10 to 20 characters. Write an appropriate query to change the size
d) Karan wants to remove all the data from table WORKER from the
database Department. Which command will he use from the following:
i) DELETE FROM WORKER;
ii) DROP TABLE WORKER;
iii) DROP DATABASE Department;
iv) DELETE * FROM WORKER;
e)Write a query to display the Structure of the table WORKER, i.e.
name of the attribute and their respective data types.
Ans
a) Create table WORKER(WORKER_ID varchar(3), FIRST_NAME
varchar(10), LAST_NAME varchar(10), SALARY integer,
JOINING_DATE Date, DEPARTMENT varchar(10) );
b) WORKER_ID
c) alter table worker modify FIRST_NAME varchar(20);
d) DELETE FROM WORKER;
e) Desc WORKER / Describe WORKER;
Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given below:
TABLE: SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERIODSEXPERIENCE
1001 RAVI SHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GANAN PHYSICS 16/07/1999 28 3
1167 HARISH B CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16
TABLE: ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
a)
i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION =
‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
Ans
i) ENGLISH 51 PHYSICS 76 MATHS 24 CHEMISTRY 27
ii) PRIYA RAI FEMALE LISA ANAND FEMALE
iii)4
b)
i) To decrease period by 10% of the teachers of English subject.
ii) To display TEACHERNAME, CODE and DESIGNATION from tables SCHOOL and ADMIN whose gender is
male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in descending order of
experience.
v) Delete all the entries of those teachers whose experience is less than 10 years in SCHOOL table.
Ans
i) update SCHOOL set PERIODS=0.9*PERIODS;
ii) select SCHOOL.TEACHERNAME, SCHOOL.CODE, ADMIN.DESIGNATION from
SCHOOL, ADMIN where gender=’MALE’.
iii) select SUBJECT, count(*) from SCHOOL group by SUBJECT;
iv) select * from SCHOOL where DOJ>’ 01/01/1999’ order by EXPERIENCE desc;
v) delete from SCHOOL where EXPERIENCE
Connectivity
Program 1: Program to connect with database and store record of
employee and display records.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
Page : 27
OUTPUT
0. ADD RECORD
1. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000 ##
Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0 ##
Bye!! ##
Page : 28
Date : Experiment No: 18
Program 1: Program to connect with database and search employee
number in table employee and display record, if empno not found
display appropriate message.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
OUTPUT
########################################
EMPLOYEE SEARCHING FORM
########################################
ENTER EMPNO TO SEARCH :1
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 80000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found
SEARCH MORE (Y) :n
Page : 29
Date : Experiment No: 19
Program 1: Program to connect with database and update the employee
record of entered empno.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT
TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format
(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
Page : 30
OUTPUT
#####################################
### EMPLOYEE UPDATION FORM
#####################################
###
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000
## ARE YOUR SURE TO UPDATE ? (Y) :y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE ) ENTER NEW SALARY,(LEAVE
BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED
## UPDATE MORE (Y) :y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000
## ARE YOUR SURE TO UPDATE ? (Y) :y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO
CHANGE )SALES ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE )
## RECORD UPDATED
## UPDATE MORE
(Y) :Y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 90000
## ARE YOUR SURE TO UPDATE ? (Y) :Y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE ) ENTER NEW SALARY,(LEAVE
BLANK IF NOT WANT TO CHANGE ) 91000 ## RECORD
UPDATED ##
UPDATE MORE (Y) :Y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000
## ARE YOUR SURE TO UPDATE ?
(Y) :N UPDATE MORE (Y) :N
Page : 31
Date : Experiment No: 20
Program 1: Program to connect with database and delete the record of
entered employee number.
import mysql.connector as mycon
con =
mycon.connect(host='127.0.0.1',user='root',password="admin
", database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
########################################
EMPLOYEE DELETION FORM
########################################
ENTER EMPNO TO DELETE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000
## ARE YOUR SURE TO DELETE ? (Y) :y
=== RECORD DELETED SUCCESSFULLY! ===
DELETE MORE ? (Y) :y
ENTER EMPNO TO DELETE :2
Sorry! Empno not found
DELETE MORE ? (Y) :n
Page : 32
python4csip.com