vikal
vikal
Write a program to take input from user and check if it is prime or not.
def is_prime(num):
if num <= 1:
return False
if num % i == 0:
return False
return True
if is_prime(number):
else:
OUTPUT :
1
PROGRAM NO :2
num_str = str(number
print(f"{num} is a palindrome.")
return True
else:
return False
if is_palindrome(num):
OUTPUT:
2
PROGRAM NO: 3
def display_ascii():
print("Choose an option:")
print("1. Get ASCII code of a character")
print("2. Get character from an ASCII code")
choice = input("Enter your choice (1/2): ")
if choice == '1':
char = input("Enter a character: ")
if len(char) == 1:
print(f"The ASCII code of '{char}' is {ord(char)}")
else:
print("Please enter only one character.")
elif choice == '2':
try:
ascii_code = int(input("Enter an ASCII code (0-127): "))
if 0 <= ascii_code <= 127:
print(f"The character for ASCII code {ascii_code} is '{chr(ascii_code)}'")
else:
print("Please enter a valid ASCII code between 0 and 127.")
except ValueError:
print("Invalid input. Please enter a numeric ASCII code.")
else:
print("Invalid choice. Please enter 1 or 2.")
display_ascii()
3
OUTPUT:
4
PROGRAM NO: 4
Write a program to input numbers in a list and display sum of all elements of it.
OUTPUT:
5
PROGRAM NO: 5
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
n = int(input("Enter the number of terms: "))
fibonacci(n)
OUTPUT:
6
PROGRAM NO: 6
Write a program to calculate the LCM and GCD of two numbers entered by the user.
OUTPUT:
7
PROGRAM NO: 7
Write a module NUM_GEN that contains all the function definition for generating
different type of numbers between given interval. Like Prime number,Armstrong
number, strong number,perfect number, even number, odd number, composite number
etc.
def ODD(n1,n2):
L=[]
for i in range(n1,n2+1):
if i%2!=0:
L.append(i)
print("Odd numbers between",n1,"and",n2,"are",L)
def EVEN(n1,n2):
L=[]
for i in range(n1,n2+1):
if i%2==0:
L.append(i)
print("Even numbers between",n1,"and",n2,"are",L)
def PRIME(n1,n2):
L=[]
for i in range(n1,n2):
count=1
for j in range(2,i+1):
if i%j==0:
count+=1
8
if count==2:
L.append(i)
print("Prime numbers between",n1,"and",n2,"are",L)
def COMPOSITE(n1,n2):
L=[]
for i in range(n1,n2+1):
count=1
for j in range(2,i+1):
if i%j==0:
count+=1
if count>2:
L.append(i)
print("Composite numbers between",n1,"and",n2,"are",L)
def STRONG(n1,n2):
import math as m
L=[]
for i in range(n1,n2+1):
s=str(i)
sum=0
for j in s:
sum+=m.factorial(int(j))
if sum==i:
L.append(i)
print("Strong numbers between",n1,"and",n2,"are",L)
def ARMSTRONG(n1,n2):
L=[]
9
for i in range(n1,n2):
sum=0
s=str(i)
l=len(s)
for j in s:
sum+=(int(j)**l)
if sum==i:
L.append(i)
print("Armstrong numbers between",n1,"and",n2,"are",L)
def PERFECT(n1,n2):
L=[]
for i in range(n1,n2):
s=0
for j in range(1,i):
if i%j==0:
s+=j
if s==i:
L.append(i)
print("Perfect numbers between",n1,"and",n2,"are",L)
def DISARIUM(n1,n2):
L=[]
for i in range(n1,n2):
sum=0
q=0
s=str(i)[::-1]
l=len(s)
for j in s:
10
sum+=(int(s[q])**l)
q+=1
l-=1
if sum==i:
L.append(i)
print("Disarium numbers between",n1,"and",n2,"",L)
PROGRAM NO: 8
Write a program that import the module NUM_GEN created as per previous question
and generate the specific numbers as per user request.
import NUM_GEN as m
n1=int(input("Enter first number(start value): "))
n2=int(input("Enter second number(stop value): "))
print("Press 1 to generate all the odd numbers between two numbers.")
print("Press 2 to generate all the even numbers between two numbers.")
print("Press 3 to generate all the prime numbers between two numbers.")
print("Press 4 to generate all the composite numbers between two numbers.")
print("Press 5 to generate all the strong numbers between two numbers.")
print("Press 6 to generate all the armstrong numbers between two numbers.")
print("Press 7 to generate all the pefect numbers between two numbers.")
print("Press 8 to generate all the disarium numbers between two numbers.")
print("Press 0 to exit.")
while True:
c=int(input("Enter 1,2,3,4,5,6,7,8 or 0 as per your requirement: "))
if c==1:
m.ODD(n1,n2)
elif c==2:
m.EVEN(n1,n2)
11
elif c==3:
m.PRIME(n1,n2)
elif c==4:
m.COMPOSITE(n1,n2)
elif c==5:
m.STRONG(n1,n2)
elif c==6:
m.ARMSTRONG(n1,n2)
elif c==7:
m.PERFECT(n1,n2)
elif c==8:
m.DISARIUM(n1,n2)
elif c==0:
print("Program closed.")
break
else:
print("Read the above instructions and try again.")
OUTPUT:
12
PROGRAM NO: 9
Write a Program to search any word as per user choice in given string/sentence.
13
OUTPUT:
PROGRAM NO: 10
Write a program to read a text file line by line and display each word separated by '#'
f=open("nishant.txt","r")
a=f.read()
s=a.split()
for i in s:
print(i,end="#")
f.close()
OUTPUT:
14
PROGRAM NO: 11
f = open("nishant.txt", "r")
content = f.read()
vowels = "aeiouAEIOU"
vowel_count = 0
for char in content:
if char in vowels:
vowel_count += 1
f.close()
print(f"Number of vowels in the file: {vowel_count}").
15
OUTPUT:
PROGRAM NO: 12
f=open("nishant.txt","r")
a=f.read()
s=a.split(" ")
count=0
for i in s:
count+=1
print(count)
16
f.close()
OUTPUT:
PROGRAM NO: 13
Write a program to count the number of times the occurrence of 'is' word in a text file
F=open(“nishant.txt”,”r”)
A=f.read()
C=0
S=f.split(“ “)
For I in s:
If i==”is”:
C+=1
17
Print(“Number of times ‘is’ occurred is:”,c)
f.close()
OUTPUT:
PROGRAM NO: 14
Write a program to write those lines which have the character 'p' from one text file to
another text file.
f=open("nishant.txt","r")
f2=open("arya.txt",'a')
a=f.read()
s=a.split(" ")
for i in s:
18
for j in i:
if j=="p":
f2.write(j)
f.close()
f2.close()
OUTPUT :
19
PROGRAM NO: 15
import random
f=open("nishant.txt","r")
s=f.readlines()
20
d=len(s)
a=random.randint(0,d)
print(s[a])
f.close()
OUTPUT:
PROGRAM NO: 16
Write a Program to read the content of file and display the total number of consonants,
uppercase, vowels and lower-case characters.
F=open(“nishant..txt”,”r”)
A=f.read()
21
S=a.split()
For I in s:
If len(i)==1:
If i.isupper():
U +=1
Elif iislower():
L +=1
Elif I in k:
V +=1
Else:
C +=1
Else:
For j in i:
If I isupper():
U +=1
Elif i.islower():
L +=1
Elif I in k:
V+=1
Else:
C+=1
Print(“Number of vowels in file is:”,v)
Print(“Number of consonants in file is:”,c)
Print(“Number of uppercase letters in file is:”,u)
Print(“Number of lowercase letters in file is:”,1)
OUTPUT :
22
PROGRAM NO: 17
23
Count = 0
Word = “”
maxCount = 0
words =[]
file = open(“Nishant.txt”, “r”)
for line in file:
string = line.lower().replace(‘,’,”).replace(‘.”,”).split(“ “)
for s in string:
words.append(s)
for I in range(0, len(words)):
count = 1
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1
if(count > maxCount):
maxCount=count
word = words[i]
print(“Most repeated word: “ + word)
file.close()
OUTPUT :
PROGRAM NO: 18
Create a binary file with name and roll number of student and display the data by
reading the file.
import pickle
24
student_data = [
{'name': 'Aryan ', 'roll_number': 101},
{'name': 'Rikki', 'roll_number': 102},
{'name': 'Nitin', 'roll_number': 103},
{'name': 'Nishant', 'roll_number': 104}]
with open('student_data.dat', 'wb') as file:
pickle.dump(student_data, file)
with open('student_data.dat', 'rb') as file:
loaded_data = pickle.load(file)
for student in loaded_data:
print(f"Name: {student['name']}, Roll Number: {student['roll_number']}").
OUTPUT:
PROGRAM NO: 19
Write a program to search a record using its roll number and display the name of
student. If record not found then display appropriate message.
25
students = {101: "Aryan bhati",102: "nitin bhati", 103: "Rikki bhati", 104: "Nishant arya "}
def search_student(roll_number):
if roll_number in students:
return students[roll_number]
else:
return "Record not found."
roll_number = int(input("Enter roll number to search: "))
result = search_student(roll_number)
print(f"Student Name: {result}")
OUTPUT:
PROGRAM NO:20
Write a program to update the name of student by using its roll number in a binary file.
26
Import pickle
f-open(“nishant.bin”,”rb”)
w1=[]
while True:
a1=pickle.load(f)
if a1==”r5”:
break
else:
W1.append(a1)
For t in w1:
Print(t)
j-input(“Enter the roll no you want to search: “)
def mod():
for I in wl:
if i[1]==j:
print(i[0])
e=input(“Enter new name: “)
i[0]=e
mod()
for t in w1:
print(t)
f.close()
open(“nishant.bin”,”w”).close()
f=open(“nishant.bin”,”wb”)
for r in w1:
pickle.dump(r,f)
pickle.dump(“r5”,f)
f.close()
27
OUTPUT :
PROGRAM NO: 21
28
Import pickel
def entry():
with open(“Desktop/data20.dat”,”wb”) as f:
L=[]
While True:
Print(“Press 1 to enter roll number and name of student.”)
Print(“Press 0 to stop.”)
p=int(input(“Enter either 0 or 1: “))
If p==1:
roll_,no=int(input(“Enter roll number: “))
. s_name=input(“Enter student name: “)
s_,class=int(input(“Enter class: “))
. sectiom=input(“Enter section: “)
T=[roll_no,s_name,s_class, section]
L.append(T)
Elif c==0:
Print(“Data entry closed.”)
Pickle.dump(L,f)
break
else:
Print(“Enter either 0 or 1 only and try again.”)
29
Else:
print("Read above instructions and try again.")
OUTPUT:
PS C:\Users\nishant vikal python a “c:\Users\nishant vikal \Desktop\CS practical\practical
file\nishant.py”
Enter 0,1 or 2: 1
Press to stop.
Enter either 8 or 1: 1
Enter either 0 or 1: 1
Press 0 to stop.
Press 0 to stop.
Enter 6 or 1:1
Enter 0 or 1:0
Program closed.
30
PROGRAM NO: 22
Write a program to read data from a csv file and write data to a csv file.
Import csv
F=open(“nishant_1”,”r”)
Fl=open(“nishant_2”,”w”)
Frer-csv.reader(f)
Print(“The following data is written in second csv file: “)
Fw=csv.writer(fl)
D=next(frer)
Fw.writerow(d)
For I in frer:
If len(i)>0:
Print(i)
Fw.writerow(i)
f.close()
fl.close()
OUTPUT :
31
PROGRAM NO: 23
import lib
a=int(input("Enter a number: "))
b = (input("Enter another number: "))
d = lib.add(a,b)
print("The sum of two numbers is",d)
Library file:
def add (x, y)
return x + y
OUTPUT:
32
PROGRAM NO: 24
Write a python program to implement searching methods based on user choice using a
list data- structure. (linear/binary).
33
Result=binary_search(L,x)
If result=-1:print(“Element is present at index”,str(result))
Else:
Print(“Element is not present in array”)
Else:
Print(“Run the program again and enter 1 or 2.”)
OUTPUT
34
PROGRAM NO: 25
Read a text file line by line and display each word separated by a #.
f=open("nishant.txt")
a=f.read()
s=a.split()
for i in s:
print(i,end="#")
f.close()
OUTPUT:
35
PROGRAM NO: 26
Remove all the lines that contain the character 'a' in a file and write it to another file.
OUTPUT:
36
PROGRAM NO: 27
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
With open(“Desktop/data27.dat”,”wb”) as f:
L=[]
While True:
Print(“Press 1 to enter roll number and name of student.”)
Print(“Press 0 to stop.”)
C=int(input(“Enter either 0 or 1: “))if c==1:
N=int(input(“Enter roll number: “))
M=input(“Enter student name: “)
D={n:m}
L.append(d)
Elif c==0:
Print(“Data entry closed.”)
Break
Else:
Print(“Enter either 0 or 1 only and try again.”)
Pickle.dump(L,f)
With open(“Desktop/data27.dat”,”rb”) as f:
L=pickle.load(f)
Print(L)
Print(“Press 1 to enter roll number for searching.”)
Print(“Press 0 to stop.”)
While True:
37
C=int(input(“Enter 0 or 1: “))
If c==1:
N=int(input(“Enter roll number to search: “))
For I in L:
If n in i.keys():
G=i[n]
Break
Else:
G=None
If g==None:
Print(“Enter valid roll number.”)
Else:
Print(g)
Elif c==0:
Print(“Program closed.”)
Break
Else:
Print(“Read above instructions and try again.”).
38
OUTPUT:
PS C:\Users\nishant vikal python -u “c:\Users\nishant vikal\Desktop\CS practical\practical
file\nishant.py”
Press 1 to enter roll number and name of student.
Press 0 to stop.
Enter either 0 or 1:1
Enter roll number: 1
Enter student name: Aryan
Press 1 to enter roll number and name of student.
Press to stop.
Enter either 0 or 1: 1
Enter roll number: 2
Enter student name: Nishant
Press 1 to enter roll number and name of student.
Press to stop.
Enter either 0 or 1:0
Data entry closed.
[[1: ‘Aryan’), (2: ‘Nishant’}]
Press 1 to enter roll number for searching.
Press 0 to stop.
Enter & or 1: 1
Enter roll number to search: 1
Aryan
Enter 0 or 1: 1
Enter roll number to search: 9
Enter valid roll number.
39
Enter 0 or 1:0
Program closed.
PROGRAM NO: 28
Create a binary file with roll number, name and marks. Input a roll number and update
the marks
Import pickle
With open(“Desktop/data28.dat”,”wb”) as f:
L=[]
While True:
Print(“Press 1 to enter roll number, name and marks of student.”)
Print(“Press 0 to stop.”)
C=int(input(“Enter either 0 or 1: “))
If c==1:
N=int(input(“Enter roll number: “))
S=input(“Enter student name: “)
M=int(input(“Enter marks: “))
D=[n,s,m]
L.append(d)
Elif c==0:
Print(“Data entry closed.”)
Break
Else:
Print(“Enter either 0 or 1 only and try again.”)
Pickle.dump(L,f)
With open(“Desktop/data28.dat”,”rb”) as f:
L=pickle.load(f)
Print(L)
40
Print(“Press 1 to enter roll number and update marks.”)
Print(“Press any other key to exit.”)
C=int(input(“Enter 1 or any key: “))
If c==1:
N=int(input(“Enter roll number to search: “))
M=int(input(“Enter new marks: “))
For I in L:
If i[0]==n:
I[2]=mprint(L)
Else: print(“Program closed.”)
OUTPUT:
PS C:\Users\nishant vikal python -u “c:\Users\nishant vikal\Desktop\CS practical\practical
file\nishant.py”
Press 1 to enter roll number, name and marks of student.
Press 0 to stop.
Enter either 0 or 1: 1
Enter roll number: 1
Inter student name: aryan
Press 1 to enter roll number, name and marks of student.
Press 0 to stop.
Enter either 0 or 1:1
Enter roll number: 2
Enter student name : nitin
Enter marks: 75
Press 1 to enter roll number, name and marks of student.
Press O to stop.
Inter either 0 or 1:0
Data entry closed.
[[‘1’, ‘aryan’, 42], [2, ‘nitin’, 75]]
41
Press 1 to enter roll number and update marks.
Press any other key to exit.
Enter 1 or any key: 1
Enter roll number to search: 1
Enter new marks: 81
[[1, aryan’, 81], [2, ‘nitin ‘, 75]]
PROGRAM NO: 29
Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
import random
for i in range(10):
a=random.randrange(1,7)
print(a)
OUTPUT:
42
PROGRAM NO: 30
Create a CSV file by entering user-id and password, read and search the password for
given user id.
import csv
with open("user.csv","w") as f:
print("Enter 1 to add user-id and password.")
print("Enter any other key to stop.")
while True:
p=int(input("Enter key: "))
if p==1:
uid=input("Enter user-id: ")
password=int(input("Enter password: "))
d=[uid,password]
w=csv.writer(f)
w.writerow(d)
else:
break
with open("user.csv","r") as f:
uid=input("Enter user-id to search: ")
r=csv.reader(f)
for i in r:
if uid in i:
g=i[1]
43
break
else:
g=None
if g==None:
print("No entry found with given user-id.")
else:
print(g)
OUTPUT:
44
PROGRAM NO: 31
Create a student table and insert data. Implement the following SQL commands on the student table:
O ALTER table to add new attributes / modify data type / drop attribute
O GROUP BY and find the min, max, sum, count and average
Use cs_25;
create table students(roll_no int not null primary key, s_name varchar(25), class int,
marks int, s_sub varchar(20));
INSERT INTO students values(1, 'nishant', 10, 70, 'Mathematics');
INSERT INTO students values(2, 'khushi', 09, 50, 'Science');
INSERT INTO students values(5, 'aryan', 10, 90, 'Science');
INSERT INTO students values(6, 'Vicky', 11, 40, 'Mathematics');
INSERT INTO students values(7, 'rikki', 12, 80, 'English');
INSERT INTO students values(10, 'sanjeev', 09, 60, 'CS');
INSERT INTO students values(11, 'harvinder', 10, 80, 'CS');
INSERT INTO students values(12, 'sachin', 11, 70, 'English');
ALTER table students ADD section char(1);
ALTER table students MODIFY s_sub varchar(15);
ALTER table students DROP section;
45
UPDATE students SET class=12 where roll_no=1;
UPDATE students SET class=12, marks=marks+10 where (roll_no=2 or roll_no=5);
SELECT roll_no, s_name, marks from students ORDER BY roll_no ASC;
SELECT roll_no, s_name, marks from students ORDER BY s_name DESC;
DELETE FROM students where roll_no=2;
SELECT s_sub as subject, min(marks) as minimum_marks from students where roll_no<15
GROUP BY s_sub;
SELECT s_sub as subject, max(marks) as maximum_marks from students where roll_no<15
GROUP BY s_sub;
SELECT s_sub as subject, sum(marks) as total_marks from students where roll_no<15
GROUP BY s_sub;
SELECT s_sub as subject, count(marks) as std_count from students where roll_no<15
GROUP BY s_sub;
SELECT s_sub as subject, avg(marks) as average_marks from students where roll_no<15
GROUP BY s_sub;
OUTPUT
46
47
PROGRAM NO: 32
Write a python MYSQL connectivity program that can create a database named as
Comp_Sci.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="Execution")
mycursor=mydb.cursor()
mycursor.execute("create database Comp_Sci;")
mydb.commit()
print("Comp_Sci database created.")
OUTPUT :
PS C:\Users\nishant> python -u “c:\Users\nishant\Desktop\CS practical\practical
file\nishant.py”
48
PROGRAM NO: 33
Write a python MYSQL connectivity program insert record in table students having following
fields:
Roll_No Integer
S_Name varchar(20)
S_class char(4)
S_Marks Integer
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="Execution",databas
e="Comp_Sci")
mycursor=mydb.cursor()
mycursor.execute("create table students(Roll_No int, S_Name varchar(20), S_class char(4),
S_Marks int);")
print("Table 'students' created.")
49
mycursor.execute("insert into students values(1,'arya','XII',70);")
mycursor.execute("insert into students values(2,'sarthak’,'XI',60);")
mycursor.execute("insert into students values(5,'nishu','X',70);")
mycursor.execute("insert into students values(10,'nishant’','XI',80);")
mycursor.execute("insert into students values(12,'khushi','XII',90);")
print("Records inserted successfully.")
mydb.commit()
OUTPUT
PS C:\Users\Sudhir Pandey> python -u “c:\Users\niahant\Desktop\CS practical\practical
file\34.py”
(1, ‘arya’, ‘XII’, 70)
(2, ‘sarthak’, ‘XI’, 60)
(5, ‘nishu’, ‘X’, 70)
(10, ‘nishant’, ‘XI’, 80)
(12, ‘khushi’, ‘XII’, 90)
PROGRAM NO: 34
Write a python MYSQL connectivity program that can display all records from tables
students from database named as Comp_Sci
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="Execution",databas
e="Comp_Sci")
mycursor=mydb.cursor()
mycursor.execute("select * from students;")
myrecords=mycursor.fetchall()
for i in myrecords:
print(i)
50
OUTPUT:
PS C:\Users\nishant vikal> python -u “c:\Users\nishant \Desktop\CS practical\practical
file\nishant.py”
Table ‘students’ created.
Records inserted successfully.
Roll_No S_NAME S_Class S_Marks
1 Aryan XII 70
2 Sarthak XI 60
5 Nishu X 70
10 Nishant XI 80
12 Khushi XII 90
PROGRAM NO: 35
Write a python MYSQL connectivity program to search a record from tables students
from database named as Comp_Sci on the basis of roll_no.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="Execution",databas
e="Comp_Sci")
mycursor=mydb.cursor()
mycursor.execute("select * from students;")
myrecords=mycursor.fetchall()
n=int(input("Enter roll number to search record: "))
for i in myrecords:
if i[0]==n:
print(i)
51
OUTPUT:
PS C:\Users\nishant> python -u “c:\Users\nishant\Desktop\CS practical\practical
file\nishant.py”
Enter roll number to search record: 1
(1, ‘arya’, ‘XII’, 70)
PS C:\Users\nishant> python -u “c:\Users\nishant\Desktop\CS practical\practical
file\nishant.py”
Enter roll number to search record: 2
(2, ‘sarthak’, ‘XI’, 60)
PS C:\Users\nishant> python -u “c:\Users\nishant\Desktop\CS practical\practical
file\nishant.py”
Enter roll number to search record: 5
(5, ‘nishu’, ‘X’, 70)
52