Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views22 pages

CS FILE 12

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

QUES 26:Program to read and display file content line by line

with each word separated by “#”


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

QUES 27:Program to read the content of file line by line and


write it to another file Except for the lines contains “a” letter in it.
ANS:
f1 = open("file1.txt")
f2 = open("file2copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print("## File Copied Successfully! ##")
f1.close()
f2.close()
“India is my countryI love python
Python learning is fun “
OUTPUT:
QUES 28:Program to read the content of file and display the total
number of consonants, uppercase, vowels and lower case
characters.
ANS:
f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
QUES 29:Program to create binary file to store Rollno and Name,
Search any Rollno and display name if Rollno found otherwise
“Rollno not found”
ANS:
import pickle
D={}
f=open("Studentdetails.dat","wb")
def write():
while True:
rno = int(input("Enter Roll no : "))
n = input("Enter Name : ")
D['Roll_No']=rno
D['Name'] = n
pickle.dump(D,f)
ch = input("More ? (Y/N)")
if ch in 'Nn':
break
f.close()
def Search() :
found = 0
rollno= int(input("Enter Roll no Whose name you want to
display :"))
f = open("Studentdetails.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec['Roll No']==rollno:
print(rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry not Found....")
f.close()
write()
Search()
OUPUT:

QUES 30:Program to create binary file to store Rollno, Name and


Marks and update marks of entered Rollno.
ANS:
import pickle
def Write():
f = open("Studentdetails.dat", 'wb')
while True:
r =int(input ("Enter Roll no : "))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record, f)
ch = input("Do you want to enter more ?(Y/N)")
if ch in 'Nn':
break
f.close()
def Read():
f = open("Studentdetails.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f = open("Studentdetails.dat", 'rb+')
rollno = int(input("Enter roll no whoes marks you want to
update"))
try:
while True:
pos=f.tell()
rec = pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Update Marks:"))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
#print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()

OUTPUT:
QUES 31:Create a CSV file by entering user-id and password,
read and search the password for given user- id.
ANS:
import csv
with open("user_info.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the
program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
Break

OUTPUT:
QUES 32:Wap to read all content of “student.csv” and display
record of only those student who scored more than 80
marks.record stored in student is in format: roll no,name,marks.
Ans:
Import csv
F=open(“student.csv”,”r”)
d=csv.reader(f)
next(f)
print("student scored more than 80")
print()
for i in d:
if int(i[2])>80:
print("roll no=",i[0])
print("name=",i[1])
print("mark=",i[2])
print("----------------")
f.close()
QUES 33:Write a function that takes a number n and then
returns a randomly generated number having exactly n digits
(not starting with zero) e.g., if n is 2 then function can randomly
return a number 10-99 but 07, 02 etc. are not valid two digit
numbers.
ANS:
import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)
n = int(input("Enter the value of n:"))
random_number = generate_number(n)
print("Random number:", random_number)

OUTPUT:
QUES 34:Write a function that takes two numbers and returns
the number that has minimum one's digit.
[For example, if numbers passed are 491 and 278, then the
function will return 491 because it has got minimum one's digit
out of two given numbers (491's 1 is < 278's 8)].
ANS:
def min_ones_digit(num1, num2):
ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
result = min_ones_digit(num1, num2)
print("Number with minimum one's digit:", result)
OUTPUT:
QUES 35:WAP to demonstrate the concept of variable length
Argument to calculate sum and product of the first 10 no.
ANS:
def sum10(*n):
total=0
for i in n:
total=total+i
print("sum of first 10 no:",total)

def product10(*n):
pr=1
for i in n:
pr=pr*i
print("product of first 10 no.:",pr)
sum10(1,2,3,4,5,6,7,8,9,10)
product10(1,2,3,4,5,6,7,8,9,10)
OUTPUT:

QUES 36:WAP to check number is prime or not


ANS:
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
OUTPUT:
Ques 37:Python function to check if a number is palindrome
or not
ANS:
def palindromeCheck(num):
temp = num
rev = 0
while(num != 0):
r = num%10
rev = rev*10+r
num = num//10
if(rev == temp):
print(temp, "is a palindrome number")
else:
print(temp, "is not a palindrome number")
palindromeCheck(131)
palindromeCheck(34)
OUTPUT:

QUES 38:Python function to find the factorial of a number


ANS:
def factorial(n):
fact = 1
while(n!=0):
fact *= n
n = n-1
print("The factorial is",fact)
inputNumber = int(input("Enter the number: "))
factorial(inputNumber)
OUTPUT:
QUES39:Write a program to reverse a string using stack.
ANS:
def push(stack, item):
stack.append(item)
def pop(stack):
if stack == [ ]:
return
return stack.pop()
def reverse(string):
n = len(string)
stack = [ ]
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string
string = input("Enter a string: ")
print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)

OUTPUT:
QUES 40:Write a program to create a Stack for storing only odd
numbers out of all the numbers entered by the user. Display the
content of the Stack along with the largest odd number in the
Stack.
ANS:
def push(stack, item):
stack.append(item)

def pop(stack):
if stack == [ ]:
return
return stack.pop()

def oddStack(num):
if num % 2 == 1:
push(stack, num)

def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large

n = int(input("How many numbers?"))


stack = [ ]
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)
OUTPUT:

QUES 41: Python program to implement stack operations.


ANS:
def is Empty (stk):
if stk == [ ]
return True
else:
returns False
def push (stk, item) :
stk. append (item)
top = len (stk) -1
def pop (stk):
if is Empty (stk) :
return “underflow”
else:
item = stk. Pop ( )
if len (stk) == 0:
top = None
else:
top = len (stk) -1
return item
def peek (stk) :
if is Empty (stk) :
return “underflow”
else:
top = len (stk) -1
return stk [top]
def Display (stk) :
if is Empty (stk) :
print (:stack empty”)
else:
top = len (stk) -1
print (stk[top], “<- top” )
for a in range (top- 1, -1, -1 ) :
print (stk [a])
#_main_
stack = [ ]
top = None
While True:
print (“STACK OPERATIONS”)
print (“1. Push”)
print (“2. Pop”)
print (“3. Peek”)
print (“4. Display stack”)
print ( “5. Exit”)
ch = int (input (“Enter your choice (1-5) :” ) )
if ch == 1 :
item = int (input (“Enter item:” ) )
push (stack, item)
elif ch == 2 :
item = pop (stack)
if item ==”underflow”
print (“underflow” : stack is empty !” )
else:
print (“popped item is”, item)
elif ch == 3:
item = peek (stack)
if item ==”underflow”
print (“underflow! Stack is empty!”)
else:
print (“Topmost item is”, item)
elif ch == 4:
Display (stack)
elif ch == 5:
break
else:
print (“Invalid choice!” )

QUES 42:Write a program to implement a stack for the employee


details (empno, name).
ANS:
employee=[]
def push():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop()
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
OUTPUT:

QUES 43:Program to connect with database and store record of


employee and display records.
ANS:
import mysql.connector as mycon
con = mycon.connect(host='localhost', user='root',
password="root")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name
varchar(20), dept varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employe
values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()

print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"D
EPARTMENT", "%10s"%"SALARY")
for row in result:

print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"
%10 s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
Output:

Ques 44: Program to connect with database and search employee


number in table employee and display record, if empno not
found display appropriate message.
Ans:import mysql.connector as mycon
con = mycon.connect(host='localhost', user='root',
password="root", database="company")

cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where
empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME","%15s"
%"DEPARTMENT", "%10s"%"SALARY")
for row in result:

print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2]
,"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")

Output:

You might also like