[go: up one dir, main page]

0% found this document useful (0 votes)
40 views51 pages

Computer Science (083) : Lab File

desc

Uploaded by

hbbtlotr1973
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)
40 views51 pages

Computer Science (083) : Lab File

desc

Uploaded by

hbbtlotr1973
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
You are on page 1/ 51

COMPUTER SCIENCE (083)

LAB FILE
SESSION: 2023-24

Submitted To: Ms. Sonam Agarwal


HOD: ICT

Submitted By: Elina Chandola


Class: XII-A
INDEX

S.No PROGRAM PAGE SIGNATURE


NUMBER
1. Write a program to input names of ‘n’
students and store them in tuple also
input them from the user and find if these
students are present in the tuple or not

2. Write a program to find the no. of times


an element occurs in a list

3. Determine if a number is a perfect


number, armstrong number or
palindrome.

4. Write a program that reads a line and


counts the number of lowercase,
uppercase, alphabets and digits.

5. Write a program to make * pattern

6. Write a program to make 123... pattern

7. Write a program to create a dictionary with


Roll.no., name, and marks of n students in a
class and display the names of students with
marks above 75.

8. Write a program to create a 3rd dictionary


from the 2 dictionaries having same
common keys in a way such that the
values of common keys

9. A tuple stores marks of a student n 5


subjects write a program to calculate the
grade of the student as per the following.

10. Program to input 2 lists and display the


new elements from both the lists
combined along with its index.
11. Count the number of vowels and
consonants in a string

12. Write a program for creating a 2D list

13. Write a program to input a string and


print each individual word with its length

14. Write a program to input a string which


has some digits, calculate the sum of the
digits present in the string.

15. Write a program to calculate multiples of


any number.

16. Write a program to calculate LCM and


HCF using function.

17. Write a program to print whether the


number is prime or composite.

18. Write a program to take n as input and


generate a random number having n
digits.

19. Write a function to write Fibonacci series.

20. Write function of ATM.

21. Write a function to check if the user input


value is positive or negative.

22. Write function to calculate area of


rectangle.

23. Write a program of factorial.

24. Write a program to read a file first 30


characters and print that.

25. Write a program to read entire content.

26. Write a program which reads n bytes and


reads some more bytes from the last
position read.
27. Write a program to read the first three
lines line by line.

28. Write a program to calculate the number


of lines in a file.

29. Write a program to create a file that holds


some student data.

30. Write a program to display the size of the


file in bytes.

31. Write a program to read a text file line by


line and display each word separated by
#.

32. Write a program to read the complete file


in form of a list

33. Write a program to read the complete file


line by line

34. Write a program to create a CSV file to


store student data, (Roll.no, name, and
marks). Obtain data from user and write
the file records.

35. Write a program to demonstrate


exception handling.

36. Write a program for raising an error in a


program.

37. Write a program to implement stack


functions.

38. Write a program to create a table in SQL.

39. Write a program to perform the given


functions.

40. Create table library and answer the


queries asked.

41. Write SQL commands for the given table.


42. Create table employee and answer the
queries asked.

43. Create table “INVENTORY” and answer


the queries asked.

44. Create table “STUDENT” and answer the


queries asked.

45. Write a program to establish a connection


in SQL using Python.
Program #1

Write a program to input names of ‘n’ students and store them in tuple also input them
from the user and find if these students are present in the tuple or not.

name = tuple()
n = int(input("How many names do you want to enter?: "))
for i in range(0, n): num = input("> ")
name = name + (num,)
print("\nThe names entered in the tuple are:")
print(name)
search=input("\nEnter the name of the student you want to search? ")
if search in name:
print("The name",search,"is present in the tuple")
else:
print("The name",search,"is not found in the tuple")
Program #2

Write a program to find the number of times an element occurs in a list.

def countX(lst, x):


count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x =8
print('{} has occurred {} times'.format(x, countX(lst, x)))
Program #3

Determine if number is a perfect number, Armstrong number or a palindrome.

a = input("Enter the number: ")


n = int(a)
x=0
c=0
if str(a) == str(a[::-1]):
print(f"{n} is a palindrome")
else:
print(f"{n} is not a palindrome")
for i in str(n): # Fix: iterate over the digits of n
b = int(i)
x += b ** 3
if x == n:
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
for j in range(1, n):
if n % j == 0:
c += j
if c == n:
print(f"{n} is a perfect number")
else:
print(f"{n} is not a perfect number")
Program #4

Write a program that reads a line and counts the number of lowercase, uppercase,
alphabets, and digits.

n=str(input("enter the one character string:"))


lc=0
uc=0
d=0
for i in n:
if i>='a' and i<='z':
lc=lc+1
elif i>='A' and i<='Z':
uc=uc+1
elif i>='0' and i<='9':
d=d+1
else:
continue
print("Lowercase letters :",lc,"Uppercase letters :",uc,"Digits:",d)
Program #5

Write a program to make a * pattern

a = int(input("Enter the number of rows: "))


for i in range(a+1):
for j in range(i):
print("*", end="")
print("")

Program #6

Write a program to make 1,2,3…pattern

​a = int(input("Enter the number of rows: "))


for i in range(1, a+1):
for j in range(1, i+1):
print(j, end=" ")
print("")
Program #7

Write a program to create a dictionary with the Roll.No, name, and marks of n students in
a class and display the names of students with marks above 75.

no_of_std = int(input("Enter number of students: "))


result = {}
for i in range(no_of_std):
print("Enter Details of student No.", i+1)
roll_no = int(input("Roll No: "))
std_name = input("Student Name: ")
marks = int(input("Marks: "))
result[roll_no] = [std_name, marks]
print(result)
for student in result:
if result[student][1] > 75:
print("Student's name who get more than 75 marks is/are",(result[student][0]))
Program #8

Write a program to create a 3rd dictionary from 2 dictionaries having same common keys
in a way such that the values of common keys.

def Merge(dict1, dict2):


return(dict2.update(dict1))
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
print(Merge(dict1, dict2))
print(dict2)
Program #9

A tuple stores marks of a student in 5 subjects, write a program to calculate the grade of
the student as per the following:

AVERAGE GRADE

>=75 ‘A’

60-74.9 ‘B’

50-59.9 ‘C’

<50 ‘D’

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=75):
print("Grade: A")
elif(avg>=60 and avg<75):
print("Grade: B")
elif(avg>=50 and avg<60):
print("Grade: C")
else:
print("Grade: D")
Program #10

Write a program to input 2 lists and display the new elements from both the lists combined
along with its index.

def common_member(a, b):


result = [i for i in a if i in b]
return result
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print("The common elements in the two lists are: ")
print(common_member(a, b))
Program #11

Count number of vowels and consonants in a string.

a = input("Enter your string: ")


v =0
c=0
for i in a:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u" or i == 'A'or i == 'E'or i == 'I'or i ==
'O'or i == 'U':
v =v +1
else:
c = c+1
print ("Number of consonants are:",c)
print ("Number of vowels are:",v)

Program #12

Write a program for creating a 2-D list.

rows, cols = (5, 5)


x = [[0]*cols]*rows
print(x)
Program #13

Write a program to input a string and print each individual word with its length.
def splitString (str):
str = str.split (' ')
for words in str:
print (words," (", len (words), ")")
str = "Hello World How are you?"
splitString(str)

Program #14

Write a program to input a string which has some digits, calculate the sum of the digits
present in the string.

string = input("Enter any string: ")


sumdigit = 0
for x in string:
if x.isdigit():
sumdigit += int(x)
print("Sum of digits =", sumdigit)
Program #15

Write a program to calculate multiples of any number.


a = int(input("Enter the number to find multiples for: "))
b = int(input("Enter the number of multiples required: "))
c=0
for i in range (b):
i = i+1
c = a*i
print (c)
Program #16

Write a program to calculate LCM and HCF using function.

def hcf(a, b):


if a >= b:
h =b
if a < b:
h =a
while h <= a and h <= b:
if a % h == 0 and b % h == 0:
return h
else:
h -= 1
def lcm(m, n):
t = (m * n) / hcf(m, n)
return t
x = int(input("enter the first number: "))
y = int(input("enter the second number: "))
print(f"the hcf of {x} and {y} is {hcf(x, y)}.\n"
f"the lcm of {x} and {y} is {lcm(x, y)}.")
Program #17

Write a function to print whether the number is prime or composite.

def func(a):
k =0
for i in range(2,a):
if a%i == 0:
k += 1
else:
continue
if k == 0:
return 0
else:
return 1
x = int(input("enter the number: "))
if func(x)==0:
print("the number is prime")
else:
print("the number is composite")
Program #18

Write a program which takes n as input and generates a random number having n digits.

import random
def func(n):
k = ""
for i in range(1,n+1):
x = random.randint(0,9)
j = str(x)
k = k+j
t = int(k)
return t
a = int(input("enter the number: "))
print(func(a))
Program #19

Write a program to write Fibonacci series.

def func(n):
a=0
b =1
if n == 1:
print(0)
elif n>0 :
for i in range(n):
c = a+b
print(a)
a=b
b =c
else:
print("error")
k = int(input("enter the number of terms: "))
func(k)
Program #20

Write functions of ATM

user = {'pin': 3011, 'balance':50000}


def widthdraw_cash():
while True:
amount = int(input("Enter the amount of money you want to widthdraw: "))
if amount > user['balance']:
print("You don't have sufficient balance to make this widthdrawal")
else:
user['balance'] = user['balance'] - amount
print(f"{amount} Dollars successfully widthdrawn your remaining balance is
{user['balance']} Dollars")
print('')
return False
def balance_enquiry():
print(f"Total balance {user['balance']} Dollars")
print('')
def deposit_cash():
amount = int(input("Enter the amount of money you want to deposit: "))
user['balance'] = user['balance'] + amount
print(f"{amount} Dollars successfully deposited your remaining balance is {user['balance']}
Dollars")
print('')
is_quit = False
print('')
print("Welcome to the ATM")
pin = int(input('Please enter your four digit pin: '))
if pin == user['pin']:
while is_quit == False:
print("what do you want to do")
print(" Enter 1 to Widthdraw Cash \n Enter 2 for Balance Enquiry \n Enter 3 to Quit\n Enter
4 to deposit cash")
query = int(input("Enter the number corresponding to the activity you want to do: "))
if query == 1:
widthdraw_cash()
elif query == 2:
balance_enquiry()
elif query == 3:
is_quit = True
elif query == 4:
deposit_cash()
else:
print("Please enter a correct value shown")
else:
print("Entered wrong pin")
Program #21

Write a function to check if the user input value is positive or negative.

def check(n):
if n>0:
print("positive")
elif n<0:
print("negative")
else:
print("zero")
k = int(input("enter the number: "))
check(k)

Program #22

Write a function to calculate the area of a rectangle.

def area(l,b):
ar = l * b
return ar
a = int(input("enter the length: "))
b = int(input("enter the breadth: "))
print(area(a,b))
Program #23

Write a program of factorial.

​def factorial(a):
f=1
if a ==0:
f=1
elif a==1:
f=1
elif a<0:
f='invalid input'
else:
for i in range(1,a+1):
f=f*i
return f
y=int(input("Enter number: "))
print(factorial(y))

Program #24

Write a program to read a file first 30 characters and print that.

a=open("/Users/admin/Desktop/text.txt",'r')
b=a.read(30)
print(b)
a.close()
Program #25

Write a program to read entire content

a=open("/Users/admin/Desktop/text.txt",'r')
b=a.read()
print(b)
a.close()
Program #26

Write a program which reads n bytes and then reads some more bytes from the last
position read.

a=open ("/Users/admin/Desktop/text.txt",'r')
x=int(input("Enter number of bytes you want to read: "))
b=a.read(x)
print(b)
c=a.read(10)
print(c)
a.close

Program #27

Write a program to read first three lines line by line

a=open("/Users/admin/Desktop/text.txt",'r')
b=a.readline()
print(b)
c=a.readline()
print(c)
d=a.readline()
print(d)
a.close()
Program #28

Write a program to calculate the number of lines in a file.

a = open(r"/Users/admin/Desktop/text.txt","r")
b =0
c = a.readlines()
d = len(c)
for i in range (d):
b =b +1
print (b)
a.close()

Program #29

Write a program to create a file that holds some student data.

a = open(r"/Users/admin/Desktop/text.txt","w")
b = int(input("Enter number of students required: "))
for i in range (b):
c = input("Enter Name: ")
a.write(c)
a.write("\n")
a.close()
Program #30

Write a program to display the size of the file in bytes.

a = open(r"/Users/admin/Desktop/text.txt","r")
b =0
c = a.read()
d = len(c)
print ("Length of file in bytes: ",d)
a.close()
Program #31

Write a program to read a text file line by line and display each word separated by #.

a = open(r"/Users/admin/Desktop/text.txt","r")
while a:
b = a.readlines()
for i in b:
c = i.split()
for j in c:
print (j + "#",end="")
a.close()

Program #32

Write a program to read the complete file in the form of a list.

a = open(r"/Users/admin/Desktop/text.txt","r")
b = a.readlines()
print(b)
a.close()
Program #33

Write a program to read the complete file line by line.

a = open(r"/Users/admin/Desktop/text.txt","r")
while a:
b = a.readline()
print (b,end="")
a.close()
Program #34

Write a program to create a CSV file to store student data (Roll.no., Name, and marks),
obtain data from user and write the file records.

import csv
def collect_student_data():
roll_no = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
return [roll_no, name, marks]
def write_to_csv_file(data):
with open('student_data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(data)
while True:
student_data = collect_student_data()
write_to_csv_file(student_data)
choice = input("Do you want to enter data for another student? (y/n): ").lower()
if choice != 'y':
break
Program #35

Write a program to demonstrate exception handling.

try:
a = int(input("Enter your number: "))
b = int(input("Enter your number: "))
print (a/b)
except ZeroDivisionError:
print ("Don't divide by zero")
else:
print ("All Good")
finally:
print ("BYE BYE")
Program #36

Write a program for raising an error in a program.

a = input("Enter a string: ")


b =3
if b > len(a):
raise IndexError
print ("No Execution")
else:
print (len(a))
Program #37

Write a program to implement stack functions.

def PUSH (s,e):


s.append(e)
return s
def POP (s):
if s == []:
print ("Underflow")
else:
e = s.pop()
return s
stack = []
c = True
while c == True:
print ("Enter your choice")
print ("1, PUSH")
print ("2, POP")
print ("3, EXIT")
a = int(input("Enter your choice: "))
if a == 1:
b = input("Enter element: ")
print(PUSH(stack,b))
elif a==2:
print(POP(stack))
elif a==3:
c = False
Program #38

Write a to create a table in SQL.

create table new_employee (ECODE int (10),NAME char(20), DESIG varchar(29), SGRADE
varchar(20), DOJ date, DOB date);
insert into new_employee values(101,'Vikrant','Executive','S03','2003-03-23','1980-01-13');
insert into new_employee values(102,'Ravi','Head-IT','S02','2010-02-12','1987-07-22');
insert into new_employee values(103,'John Cena','Receptionist','S03','2009-6-24','1983-02-24');
insert into new_employee values(105,'Azhar Ansari','GM','S02','2009-08-11','1984-03-03');
insert into new_employee values(108,'Priyam Sen','CEO','S01','2004-12-19','1982-01-19');
select*from new_employee
Program #39

Write a program to perform the given functions:

(i) To display details of all employees in descending order of their DOJ.

select * from new_employee order by doj desc;

(ii) To display NAME and DESIG of those employees whose sgrade is either ‘S02’ or ‘S03’.

select Name, Desig from new_employee where sgrade='s02' or sgrade='s03';


(iii) To display NAME, DESIG, SGRADE of those employees who joined in the year 2009.

select name, desig, sgrade from new_employee where doj like '2009%';

(iv) To display all SGRADE, ANNUAL_SALARY from table SALGRADE [where


ANNUAL_SALARY=SALARY*12]

select sgrade, salary*12 as 'ANNUAL_SALARY' from salgrade;

(v) To display number of employee working in each SALGRADE from table EMPLOYEE

select count(name), sgrade from new_employee group by sgrade;

(vi) Select MIN(DOJ), MAX(DOB) from employee;

select min(DOJ), max(DOB) from new_employee;


(vii) Select SGrade, Salary+HRA from SalGrade where Sgrade=’S02’

select Sgrade, salary+hra from salgrade where sgrade='s02';

(viii) Select count (distinct sgrade) from employee.

select count(distinct sgrade) from new_employee;

(ix) Select sum(salary), avg(salary) from salgrade.

select sum(salary), avg(salary) from salgrade;


Program #40

Create table library and answer queries asked.

(i) Rename the column “Author” as “Writer”

(ii) Add a new column called “Books”


(iii) Modify the data type of column “Qty”
Program #41

Write SQL commands for the following table:

(i) To display the names of those companies whose city is “DELHI”


(ii) To display the names of the companies in reverse alphabetical order.

(iii) To increase the prize by 1000 for customers whose names start with S?
(iv) To select different values from column “CID”

(v) select avg(qty) from customer where name like “%r%”


Program #42

Create table employee and answer the queries asked

(i) Display ename, sal, and sal added with comm from table employee

(ii) Write a query to display employee name, salary, and department number who are not
getting commission from table employee
(iii) List all department numbers in table employee

(iv) List all unique department numbers in table employee

(v) List details of all clerks who have not been assigned departments as yet
Program #43

Create table “INVENTORY” and answer the queries asked

(i) Show different categories from the column “CAT”

(ii) Write a query to display the name of the product which contains “Y” as the last
alphabet.
(iii) List the details of the product which contains 8 letters in its CAT

(iv) Write a query to display the name of product who is having “L” in its name.

(v) Display price and quantity of the product added


Program #44

Create table STUDENT and answer the queries asked

(i) Display the names of the students who are getting a grade “C” either GAME or SUPW

(ii) Display the different games offered in the school

(iii) Display the SUPW taken up by the students, whose name starts with “A”
Program #45

Write a program to establish a connection in SQL using python



import mysql.connector as sqltor
a = sqltor.connect(host = 'localhost', user = 'root', password = 'root', database = 'elina')
b = a.cursor()b.execute("Show Tables")
for i in b:
print(i)

You might also like