0% found this document useful (0 votes)
27 views

Computer Science

A variety of programming challenges and their solutions are presented, ranging from basic problems like checking number properties to more advanced tasks involving files, dictionaries, databases and SQL. Each section includes the code needed to solve the problem as well as example outputs verifying the code is working correctly.

Uploaded by

Bhuwan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Computer Science

A variety of programming challenges and their solutions are presented, ranging from basic problems like checking number properties to more advanced tasks involving files, dictionaries, databases and SQL. Each section includes the code needed to solve the problem as well as example outputs verifying the code is working correctly.

Uploaded by

Bhuwan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

COMPUTER SCIENCE

PRACTICAL
FILE

A.G.D.A.V.C.P SCHOOL

SUBMITTED TO : SUBMITTED BY :
MRS.RUCHI CHHABRA Deepak Bora
XII-A

1. Program to determine whether number is


perfect number or not
Code:
n = int(input("Enter any number to check whether it is perfect
number or not : "))
sum = 0
for i in range(1,n):
if n%i==0:
sum = sum + i

if sum == n :
print( n,"is perfect number")
else :
print( n, "is not perfect number")

output:
2. Program to check whether the given number
is armstrong or not

Code :
n = int(input("Enter any number to check whether it is an
armstrong : "))
t=n
total = 0
while t > 0 :
digit = t %10
total = total + (digit**3)
temp = temp//10
if n == total:
print( n,"is an armstrong number")
else :
print( n, "is not armstrong number")

Output :
3.Program to find smallest and largest number
from the list

Code :
mylist = []
number = int(input('How many elements to put in List: '))
for n in range(number):
element = int(input('Enter element '))
mylist.append(element)
print("Maximum element in the list is :", max(mylist))
print("Minimum element in the list is :", min(mylist))

Output :
4. create a dictionary with roll number, name
and marks of n students in a class and display
the names of students who have scored marks
above 75
Code :
n = int(input("Enter number of students :"))
result = {}
for i in range(n):
print("Enter Details of students :",i+1)
rno = int(input("Roll number :"))
name = input("Name :")
english = float(input("Enter English Marks: "))
math = float(input("Enter Math score: "))
computers = float(input("Enter Computer Marks: "))
physics = float(input("Enter Physics Marks: "))
chemistry = float(input("Enter Chemistry Marks: "))
total = english + math + computers + physics + chemistry
percentage = (total / 500) * 100
result[rno] = [name,percentage]
print(result)

for s in result:
if result[s][1]>75:
print("Following students having more than 75 marks:")
print(result[s][0])
Output :
5. User defined function to find factorial of a
given number

Code :
def factorial(num):

if num == 1:
return num
else:
return num * factorial(num - 1)
#Driver code
num=10
y=factorial(num)
print(y)

Output :
6. Write a UDF to enter the string and to check if it’s
palindrome or not using loop

Code :
def Palindrome(s):
return s == s[::-1]

# Driver code
s = "america"
ans = Palindrome(s)

if ans:
print("Yes")
else:
print("No")
Output :
7. Write a user defined function to print
fibonacci series upto n terms

Code :

def fib(nterms=2):
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
fib()
Output :
8.Write a user defined function to calculate
simple interest

Code :
def simple_interest(p,t,r):
print('The principal is', p)
print('The time period is', t)
print('The rate of interest is',r)

si = (p * t * r)/100

print('The Simple Interest is', si)


return si

# Driver code
simple_interest(8000, 6, 8)
Output :
9.Program to Read a text file line by line and
display each word separated by #.

Code :
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()

Output :
10. Read a text file and display the number of
vowels/consonants/uppercase/lowercase
characters in the file

Code :
Output :
11. Program to create a binary file to store
Rollno and name

Code :
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")

Output :
12. : Program to create binary file to store
Rollno,Name and Marks and update marks of
entered Rollno

Code :
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()

Output :
13. Program to create CSV file and store
branch,cgpa,name and year after joining of
employee

Code :
import csv
mydict =[{'branch': 'COE', 'cgpa': '9.0',
'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1',
'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3',
'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5',
'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8',
'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1',
'name': 'Sahil', 'year': '2'}]
fields = ['name', 'branch', 'year', 'cgpa']
filename = "university_records.csv"
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
writer.writeheader()
writer.writerows(mydict)

Output :
Program did not generate any output
14. Write a Program to Create a database and
table in it.
Code :
import mysql.connector as mys
mycon = mys.connect ( host = "localhost", user = "root",
password = "1234")
mycur = mycon.cursor()
query = "CREATE DATABASE emp"
mycur.execute (query)
print("New Database is Created !!")

Output :
Code :

import mysql.connector as mys


mycon = mys.connect ( host = "localhost", user = "root",
password = "1234")
mycur = mycon.cursor()
mycur.execute("USE emp")
query = "CREATE TABLE empd (EmpNo int, EmpName
Varchar(15), Dept Varchar(8), Salary int)" mycur.execute (query)
print("New Table is Created !!")
Output :
15. Write a program to update a record in a
table

Code :
import mysql.connector as mys
#mycon - connection object mycon = mys.connect (host =
"localhost", user = "root", password = "1234", database =
"emp_data")
mycur = mycon.cursor()
Job = input ("Enter the JOB Profile ---> ")
Hiredate = input ("Enter the Hiredate ---> ")
query =" UPDATE emp set Sal = Sal + (Sal * 0.05) WHERE Job =
'%s' AND Hiredate >= '%s'" % (Job ,Hiredate)
mycur.execute(query)
mycon.commit()
print("RECORD IS UPDATED as per your INPUT")
Output :
16. SQL queries
2.Write queries based on functions

1. Write a query to display cube of 5.

2. Write a query to display the number 563.854741 rounding off to the next hnudred.
3. Write a query to display dayname on which movies are going to be release

4. Write a query to display last four digits of businesscost.


5. Write a query to display weekday of release dates
3]

4]

5]
3. Consider the following table and answer the following queries
4. consider the following tables and answer the following queries

You might also like