Nothing Special   »   [go: up one dir, main page]

Cs Class 12 Codes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Question 1

Write a program in python to check a number whether it is


prime or not?

def isNumberPrime(n):
if n <= 1:
return 0
for i in range(2,n):
if n % i == 0:
return 0;
return True

n = 50
a = input("number to check:")
number to check: 103
if(isNumberPrime(n)):
print("true")
else:
print("false")

Output:
Question 2
Write a program to check a number is a palindrome or not?

test_number = int(input("Enter a Number:"))

res = str(test_number) == str(test_number)[::-1]

print(f"It is {res},that {test_number} is a palindrome!")

Output:

Question 3
Write a program to display ASCII code of a character and vice
versa

while True:
char = input("please input a single character:")
print(ord(char))

Output:
Question 4
Write a function SwapNumbers() to swap two numbers and
display the number before swapping and after swapping?

def SwapNumbers(a, b):


temp_a,temp_b = a,b
a = temp_b
b = temp_a
return(a,b)

a,b = input("Enter two numbers:").split(",",2)


print(f"Numbers Before swap, {a} and {b}")
a,b = (SwapNumbers(a,b))
print(f"Numbers after swap, {a} and {b}")

Output:
Question 5
Write a program to compute GCD and LCM of two numbers
using functions

def find_gcd(a, b):


while b != 0:
a,b = b,a%b

return a

def find_gcd(a, b):


while b != 0:
a,b = b,a%b
return a
def find_lcm(a, b):
max = a if a > b else b
while True:
if max % a == 0 and max % b == 0:
return max
max += 1

if usrinput.upper() == "GCD":
a = int(input("enter number one:"))
b = int(input("enter number two:"))
print(find_gcd(a,b))
else:
a = int(input("enter number one:"))
b = int(input("enter number two:"))
print(find_lcm(a,b))

Output:

Question 6
Write a function FACT() to calculate the factorial of an intiger

import math
def FACT(a):
fact = math.factorial(a)
return(fact)

a = int(input("enter a number:"))
fact = FACT(a)
print(f"The factorial of {a} is: {fact}")

Output:

Question 7
Write a program to generate random numbers between 1
and 6 and check whether a user won a lottery or not

import random
lottery_num = random.randrange(1,7)
lottery_usr = random.randrange(1,7)
if lottery_num == lottery_usr:
print("You won the lottery!!!")
else:
print("You lost the lottery:(")

Output:
Question 8
Write a program to count the number of vowels present in a
text file

def vowels(filename):
txt_file = open(filename,"r")
vowel = 0
vowels_list = ['a','e','i','o','u','A','E','I','O','U']
for character in txt_file.read():
if character in vowels_list:
vowel += 1
return vowel

file = input("please enter a filename:")


please enter a filename:bee_movie.txt
vowel_count = vowels(file)

print(f"the number of vowels in the file are {vowel_count}")

Output:
Question 9
Write a program to write those lines which have the
character ‘p’ from one text to another text file

file_name = input("Enter The File's Name: ")


file_read = open("bee_movie.txt", "r")
text = "p"
lines = file_read.readlines()
new_list = []
idx = 0
if text in lines:
new_list.insert(idx, line)
idx += 1
file_read.close()
if len(new_list) == 0:
print("Character was not found in the text file")
else:
lineLen len(new_list)
for i in range(lineLen):
print(end new list[i])
print()

Output:
Question 10
Write a program to count number of words in a file
number_of_words = 0

with open(rbee_movie.txt','') as file:


data = file.read()
lines = data.split()
for word in lines:
if not word.isnumeric():
number_of_words += 1
print(number_of_words)

Output:

Question 11
Write a Python program to write student data in a binary file?

import pickle
S={}
file2 = open('student.txt', 'wb')
R=int (input ('Enter roll number='))
N = input ("Enter name =')
M = float(input ("Enter marks =))
S['Rollno'] = R
S['Name'] = N
S['Marks'] = M

pickle.dump(S,file2)

file2.close()

Output:

Question 12
Write a python program to read student data from a binary
file?

import pickle
file = open("student.txt","rb")
try:
while True:
record = pickle.load(file)
except EOFError:
pass

file.close()
file= open("student.txt","rb")
print(file.read())
file.close()

Output:

Question 13
Write a python program to modify/update student data in a
binary file?

import pickle
reclst = []
f= open('student.dat"','b')

while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
R = int (input ("Enter roll number of student to update record'))
N = input ("Enter name=')
M = float(input("Enter marks ='"))
for i in range (len(reclst)):
if i['Rollno'] == R:
i['Name'] = N
i['Marks'] = M

fopen('student.dat,'wb')
for i in reclst:
pickle.dump(i,()
f.close()

Output:

Question 14
Write a python program to delete student data from binary
file?

import pickle
roll = input("Enter roll number whose record you want to delete:')
with open("student.dat","rb") as f:
list = pickle.load(f)
found = 0
1st = []
for x in list:
if roll not in x['roll']:
Ist.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(Ist, file)
print("Record Deleted")
else:
print(Roll Number does not exist)
file.close()

Output:

Question 15
Write a python program to search a student record in a
binary file?

import pickle
roll = input("Enter roll number that you want to search in binary file)
file= open('student.dat", "rb")
list-pickle.load(file)
file.close()
for x in list:
if roll in x['roll)
print("Name of student is: ['name'])
break
else:
print("Record not found")

Output:

Question 16
Write a program to perform read and write operation with
.csv file?

import csv
def readcsv(
with open(example.csv f
data= csv.reader(f)

for row in data:


print(row)
def writecsv():
with open("example.csv", mode='a', newline=") as file:
writer csv.writer(file, delimiter, quotechar
writer.writerow(['4', 'Devansh', 'Arts', '404'])

print("Press-1 to Read Data and Press-2 to Write data: ")


a=int(input())
if a==1:
readcsv()
elif a==2:
writecsv()
else:
print("Invalid value")
f.close("example.csv")

Output:

Question 17
Create a CSV file by entering user-id and password, read and
search the password for given userid

import csv
def searchcsv(id):
with open('data.csv','rt’)as f:
data = csv.reader(f)
for row in data:
if row[0]==id:
print(row[1])
break
else:
print("Userid is not present")
def writecsv():
with open('data.csv', 'a', newline=") as f:
w = csv.writer(f)
n=int(input("How many userid you want to enter: "))
for i in range(n):
print("Enter userid",i+1)
id=input()
pswd=input("Enter Password: ")
w.writerow([id,pswd])
writecsv()
userid=input("Enter userid for which you want to search password: ")
searchcsv(input("what is your id?"))
Output:

Question 18
Write a program for linear search

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search: "))
for i in range(n):
if L[i]==item:
print("Element found at the position:",i+1)
break
else:
print("Element not Found")

Output:
Question 19
Write a program to pass an integer list as stack to a function
and push only those elements in the stack which are divisible
by 7.

STACK=[]
def PUSH(L):
for i in L:
if i%7==0:
STACK.append(i)
print("The Stack is ", STACK)
M=eval(input("Enter an integer list;"))
PUSH(M)

Output:

Question 20
Write a menu based program to perform the operation on
stack in python

def push(n)
L.append(n)
print("Element inserted successfully")
def Pop():
if len(L)==0:
print("Stack is empty")
else:
print("Deleted element is: ", L.pop())
def Display():
print("The list is: ",L)
def size():
print("Size of list is: ", len(L))
def Top():
if len(L)==0:
print("Stack is empty")
else:
print("Value of top is: ", L[len(L)-1])

L=[]
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push")
print("2. Pop")
print(" 3. Display")
print(" 4. Size of Stack")
print(" 5. Value at Top")
choice=int(input("Enter your choice (1-5):"))
if choice==1:
val-input("Enter the element: ")
push(val)
elif choice-2:
Pop()
elif choice==3
Display()
elif choice==4:
size()
elif choice-S
Top()
else
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option input()
if options=='y’ or option=="Y"
var True
else:
var=False

Output:
Question 21
Create database, Show databases, USE, Create table, Show
Tables, Describe, Rename, Alter, Select, From, Where, Insert,
Update commands

mysql> CREATE DATABASE RAILWAYS;


#Command to show the available databases
mysql> SHOW DATABASES;
#Command to enter in a databse
mysql> USE RAILWAYS;
Database changed
#Create a table in the database
mysql> Create table TRAIN(Train_No int primary key, Tname
varchar(30), Source varchar(10), Destination varchar(10), fare
float(6,2),
start_date date);
#Show the available tables in the database
mysql> Show tables;
# Show the details of a table
mysql> describe Train;
# Rename/Change the name of the table
mysql> Alter table Train rename Traindetails;
#Insert row in the table
mysql> insert into Traindetails values(22454, "Rajdhani Exp",
"Mumbai", "Delhi", 2856.20, "2019-06-22");
#Show all data/rows of the table
mysql> SELECT FROM TRAINDETAILS;
#Change/Modify the fare of train to 3000.00 whose train no. is 22454
mysql> update Traindetails set fare = 3000.00 where
Train_No=22454;

Question 22
Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER
BY GROUP BY, HAVING

A. Display the name of departments. Each department should be


displayed once.
SELECT DISTINCT(Dept)
FROM EMPLOYEE;
B. Find the name and salary of those employees whose salary is
between 35000 and
40000.
SELECT Ename, salary
FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
C. Find the name of those employees who live in guwahati, surat or
jaipur city.
SELECT Ename, city
FROM EMPLOYEE
WHERE city IN('Guwahati', 'Surat','Jaipur");
D. Display the name of those employees whose name starts with 'M'.
SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE 'M%';
E. List the name of employees not assigned to any department.
SELECT Ename
FROM EMPLOYEE
WHERE Dept IS NULL;
F. Display the list of employees in descending order of employee
code.
SELECT *
FROM EMPLOYEE
ORDER BY ecode DESC;
G. Find the average salary at each department.
SELECT Dept, avg(salary)
FROM EMPLOYEE
group by Dept;

Question 23
Display the name of departments. Each department should
be displayed once.

a. Find the average salary of the employees in employee table.


SELECT avg(salary)
FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
SELECT Ename, min(salary)
FROM EMPLOYEE
WHERE sex='F';
c. Find the maximum salary of a male employee in EMPLOYEEtable.
SELECT Ename, max(salary)
FROM EMPLOYEE
WHERE sex='M';
d. Find the total salary of those employees who work in Guwahati
city.
Solution:- SELECT sum(salary)
FROM EMPLOYEE
WHERE city="Guwahati';
e. Find the number of tuples in the EMPLOYEE relation.
SELECT count(*)
FROM EMPLOYEE;

Question 24
Write a program to connect Python with MySQL using
database connectivity and perform the following operations
on data in database: CREATE a table in database

import mysql.connector
demodb =mysql.connector.connect(host="localhost", user="root",
passwd="computer", database "EDUCATION")
democursor-demodb.cursor()
democursor.execute("CREATE TABLE STUDENT (admn_no int primary
key, sname varchar(30), gender char(1), DOB date, stream
varchar(15),
marks float(4,2))")

Question 25
Write a program to connect Python with MySQL using
database connectivity and perform the following operation
on data in database:Insert record in the table

import mysql.connector
demodb = mysql.connector.connect(host="localhost", user "root",
passwd="computer", database="EDUCATION")
democursor-demodb.cursor()
democursor.execute("insert into student values (%s, %s, %s %s, %s,
%s)", (1245, 'Arush', 'M', '2003-10-04', 'science', 67.34))
demodb.commit()

Question 26
Write a program to connect Python with MySQL using
database connectivity and perform the following operation
on data in database: Fetch records from the table using
fetchone(), fetchall() and fetchmany().

FETCHONE()
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor demodb.cursor()
democursor.execute("select from student")
print(democursor.fetchone())
FETCHALL()
import mysql.connector
demodb mysql.connector.connect(host "localhost", user "root",
passwd "computer", database "EDUCATION")
democursor demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchall())
FETCHMANY()
import mysql.connector
demodb = mysql.connector.connect(host "localhost", user="root",
passwd="computer", database="EDUCATION")
democursor demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchmany(3))

Question 27
Write a program to connect Python with MySQL using
database connectivity and perform the following operation
on data in database:Update record in the table

import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor-demodb.cursor()
democursor.execute("update student set marks 55.68 where
admn_no-1356")
demodb.commit()

Question 28
Write a program to connect Python with MySQL using
database connectivity and perform the following operation
on data in database: Delete record from the table
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor demodb.cursor()
democursor.execute("delete from student where admn_no=1356")
demodb.commit()

You might also like