CS Practical 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Computer Science - 083

Final Practical File

Ali Syed 12A


Roll No - 21658436
Q1 Write a program in python to check whether a number is prime or not.

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

if num == 1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")

else:
print(num,"is not a prime number")

Q2 Write a function “str_palindrome” in python to test whether a string is a


palindrome or not

def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False

x = str(input("Enter string:"))

if is_palindrome(x) == True :
print("Palindrome")
else:
print("Not a palindrome")

Output
Enter string:racecar
Palindrome
Q3 Write a program to check whether a number is a palindrome or not.

x = int(input("Enter number:"))

temp = x
rev = 0
while temp > 0 :
rem = temp % 10
rev = (rev * 10) + rem
temp = temp // 10
if x == rev:
print("Palindrome!")
else:
print("Not a palindrome!")

Output 1234

Enter number:1234
Not a palindrome!

Q4 Write a function to calculate the factorial of an integer and invoke that


function.
def fact(n):
f = 1
for i in range(1,n+1):
f = f*i
return(f)

print(fact(5))

Output

120

Q5 Read a text file line by line and display each word separated by a #.

f = open("sample.txt",r)
a = f.read()
b = a.split()
l = len(b)
for i in b:
print(b[i], '#' , end = " ")
Output
You # are # reading # sample.txt #
Q6 Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.
f = open("sample.txt",r)
a = f.read()
l = len(a)
c = 'bcdfghjklmnpqrstvwxyz'
v = 'aeiou'
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower = 'abcdefghijklmnopqrstuvwxyz'
const = vow = uppercase = lowercase = 0

for i in range(l):
if a[i].lower() in v:
vow += 1
if a[i].lower() in c:
const += 1
if a[i] in upper:
uppercase += 1
if a[i] in lower:
lowercase += 1

print(f"No. of consonants are {const}, vowels are {vow},


uppercase letters are {uppercase}, lowercase letters are
{lowercase}.")
Output

No. of consonants are 22, vowels are 11, uppercase letters are 6,
lowercase letters are 27.
Q7 Write a program to generate random numbers between 1 and 6(simulates a
dice)
import random
r = random.randint(1,6)
print(f"The dice rolls {r}")

Output

The dice rolls 1


Q8 Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.

import pickle
print('''1.Create a binary file.\n
2.Search for a roll no.''')
choice = int(input("Choose a command"))

if choice == 1:
f.open('student.dat',wb)
entries = int(input("How many entries? : "))
for entry in range(entries):
name = str(input("Enter a name : "))
rollno = int(input("Enter a roll no. : "))
t = [name , rollno]
pickle.dump(t,f)
f.close()
print("File created")

elif choice == 2:
f.open('student.dat', 'rb')
roll_find = int(input("Roll no of the student to be found : "))
while True:
content = pickle.load(f)
if content[1] == roll_find:
print(content[0])
break
else:
print("No such Roll no found")

Q10 Write a program to remove all the lines that contain the character ‘a’ in a
file and write it to another file.
f = open('sample1.txt' ,'r')
x = f.readlines()
l = []
for i in x:
if 'a' in i:
fnew = open('sample2.txt','r+')
fnew.write(i)
a = fnew.read()
else:
l.append(i)
f.close()
f = open('ssample1.txt','w')
f.writelines(l)
f.close()
Q11 Write a program to print the largest number in a list of integers.

n = int(input("No of elements in the list : "))


l = []
for i in range(0,n):
a = int(input("Enter the number : "))
l.append(a)
print(max(l))

Output

No of elements in the list : 3


Enter the number : 1323123
Enter the number : 224323
Enter the number : 2
1323123

Q12 Create a CSV file by entering user-id and password, read and search the
password for given user id.

import csv
field = ['user_id', 'password']
rows = ['admin1','pass1'] , ['admin2','pass2'] ,
['admin3','pass3'] , ['admin4','pass4']
filename = 'userpassword.csv'
with open(filename , 'w', newline = '') as f:
csv_w = csv.writer(f, delimiter = ',')
csv_w.writerow(field)
for i in rows:
csv_w.writerow(i)
print("File created")

f = open('userpassword.csv' , 'r')
csv_reader = csv.reader(f)
ID = input("User ID : ")
for i in csv_reader:
if ID == i[0]:
print(f"Password is {i[1]}")
Output

File created
Used ID : admin1
Password is pass1
SQL Database
Q1 (i) Display the Trainer Name, City &amp; Salary in descending order of their
Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
(iii) To display number of Trainers from each city.
(iv) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER
and COURSE of all those courses whose FEES is less than or equal to 10000.
Q2p(a)To change the Price of Product with P_ID as ‘TP01’ to 850.
(b)To display the details of Products whose price is in the range of 50 to 100
(c)To display the details of those products whose name ends with ‘Wash’.
(d)To display the contents of the Product table in ascending order of Price.
(e)To insert a new row in the table Products having
SQL Connectivity Programs
Q1 Write the code given below to check the connection between Python and MySQL.

import pymysql
con=pymysql.connect(db = 'test', user = 'root', passwd = 'sql123',host 'localhost')
print(con)

Output
<pymysql.connections.Connection object at 0x000001A5345D1AD0>

Q2 To insert a record write the following code.

import pymysql
con=pymysql.connect(db ='test', user = 'root', passwd ='sql123',host = 'localhost')
cur = con.cursor()
rollno =int(input('Rollno - '))
sname=input('Student name - ')
marks=float(input('Enter marks - '))

i=cur.execute("insert into student values('%d','%s','%f')"%(rollno,sname,marks))


if i>=1:
con.commit()
print('Record saved')
con.close()

Output
Rollno - 5
Student name - Devansh
Enter marks – 100
Record saved
Q3 Write this code to update a record:

import pymysql
con=pymysql.connect(db ='test', user = 'root', passwd = 'sql123', host = 'localhost')
cur=con.cursor()

i=cur.execute("update student set marks = 92 where name = 'Ali'")


con.commit()
print('Record Updated')

Output
Record Updated

Q4 Write this code to delete a record.

import pymysql
con=pymysql.connect(db ='test', user = 'root', passwd = 'sql123', host = 'localhost')
cur=con.cursor()

rollno=int(input("Enter rollno to be deleted - "))

i=cur.execute("delete from student where rollno = '%d'"%(rollno))

if i>=1:
con.commit()
print("Record deleted")
con.close()

Output

Enter rollno to be deleted - 5


Record deleted

Q5 Write this code to display the records.

import pymysql
con=pymysql.connect(db ='test', user = 'root', passwd = 'sql123', host = 'localhost')
cur=con.cursor()

i=cur.execute("select * from student")


rs = cur.fetchall()
print(rs)

Output

((5, 'Devansh', Decimal('100')),)

You might also like