0% found this document useful (0 votes)
93 views36 pages

Practical Record - GR12 - 2022

The document contains a list of programming questions related to Python programming concepts like input/output, file handling, data structures, SQL integration etc. It includes questions on writing programs to find largest of 3 numbers, check number types, generate Fibonacci series, string operations, file reading/writing, binary file handling, random number generation, stack implementation using lists, CSV file operations and SQL commands. The questions cover basic to intermediate Python programming concepts.

Uploaded by

Ace Smoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views36 pages

Practical Record - GR12 - 2022

The document contains a list of programming questions related to Python programming concepts like input/output, file handling, data structures, SQL integration etc. It includes questions on writing programs to find largest of 3 numbers, check number types, generate Fibonacci series, string operations, file reading/writing, binary file handling, random number generation, stack implementation using lists, CSV file operations and SQL commands. The questions cover basic to intermediate Python programming concepts.

Uploaded by

Ace Smoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

INDEX

Sl.No. Program Sign

1. Write a program to input three numbers and display the


largest number.
2. Write a program to determine whether a number is a Perfect
number, an Armstrong number or a Palindrome
3. Write a program to display the terms of a Fibonacci series.

4. Write a program to input a string and determine whether it is


a palindrome or not; convert the case of characters in a
string.
5. Write a program to read a text file line by line and display
each word separated by a #
6. Write a program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the
file.
7. Write a program to remove all the lines that contain the
character 'a' in a file and write it to another file.
8. Write a program to 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.
9. Write a program to create a binary file with roll number,
name and marks. Input a roll number and update the marks.
10. Write a program to write a random number generator that
generates random numbers between 1 and 6 (simulates a
dice).
11. Write a program to Write a Python program to implement a
stack using list.
12. Write a program to create a CSV file by entering user-id and
password, read and search the password for given user-id.
13. MYSQL: Create a student table and insert data. Implement
the following SQL Commands in the student table:
 Alter table to add new attributes/Modify data type/
Drop attribute.
 Update table to modify data ORDER BY to display data
in ascending /descending order.
 DELETE to remove tuple(s) GROUP BY and find the
MIN,MAX,SUM,COUNT and AVERAGE.

14. Write a Program to integrate SQL with Python by importing


the MYSQL module record of Employee and display the
record.
15. Write a Program to integrate SQL with Python by importing
the MYSQL Module to search an employee using empno and
if present in table display record, if not display appropriate
method.

16. Write a Program to integrate SQL with Python by importing


the MYSQL Module to Update the Salary of employee using
the empno.

Q1: Write a program to input three numbers and display the largest number.
Program:
n1=input("Enter the first number to check:")
n2=input("Enter the second number to check:")
n3=input("Enter the third number to check:")

#Checking Largest
if n1>n2 and n1>n3:
print(n1," is largest.")
elif n2>n1 and n2>n3:
print(n2," is largest")
elif n3>n1 and n3>n2:
print(n3," is largest")
else:
print("You have entered equal number.")

Output:

Q2: Write a program to determine whether a number is a perfect number, an


armstrong number or a palindrome
Program:
#Perfect Number
num=int(input('Enter the number: '))
sum1=0
for i in range(1,num):
if (num%i)==0:
sum1=sum1+i
if sum1==num:
print(num, 'is a perfect number')
else:
print(num, 'is not a perfect number')
#Armstrong Number
num=int(input('Enter a number'))
order=len(str(num))
sum1=0
temp=num
while num>0:
dg=num%10
sum1+=dg**order
num=num//10
if temp==sum1:
print('Number is an armstrong number')
else:
print('Number is not an armstrong number')
#Palindrome Number
n=int(input('Enter the Number'))
rev=0
temp=n
while(n>0):
rev=(rev*10)+n%10
n=n//10
if temp==rev:
print('Palindrome Number')
else:
print('Not Palindrome ')

Output:

Q3: Write a program to display the terms of a Fibonacci series.


Program:
i=int(input("Enter the limit"))
x=0
y=1
z=1
print ("Fibonacci Series \n")
print (x,y,end=" ")
while(z<=i):
print (z, end=" ")
x=y
y=z
z=x+y

Output:

Q4: Write a program to input a string and determine whether it is a palindrome or


not; convert the case of characters in a string.
Program:
#input a string and determine whether it is a palindrome or not;
#convert the case of characters in a string.

str1=input('Enter a string')
if(str1==str1[::-1]):
print('The string is a Palindrome')
else:
print('The string is not a Palindrome')

print('String after converting the case:',str1.swapcase())

Output:

Q5: Write a program to read a text file line by line and display each word
separated by a #
Program:
def WordsSeparated():
f=open("Quotes.txt","r")
lines=f.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+'#', end='')
print()
WordsSeparated()

Output:

Q6: Write a program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Program:
def CountVCUL():
f=open("cons,upper,lower.txt","r")
V=C=U=L=0
data=f.read()
for i in data:
if i.isalpha():
if i.isupper():
U+=1
if i.islower():
L+=1
if i.lower() in 'aeiou':
V+=1
else:
C+=1
print("Vowels = ", V)
print("Consonants = ",C)
print("Uppercase = ", U)
print("Lowercase = ", L)
CountVCUL()

Output:
Q7: Write a program to remove all the lines that contain the character 'a' in a file
and write it to another file.
Program:
def Remove():
f=open("Sampleold.txt","r")
lines=f.readlines()
fo=open("Sampleold.txt","w")
fn=open("Samplenew.txt","w")
for line in lines:
if 'a' in line:
fn.write(line)
else:
fo.write(line)
print("Data updated in sample old file created sample new file")
Remove()

Output:
Q8: Write a program to 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.
Program:
import pickle
def Write():
f=open("StudentDetails.dat","wb")
while True:
r=int(input("Enter Rollno"))
n=input("Enter Name")
Data=[r,n]
pickle.dump(Data,f)
ch=input("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 Search():
found=0
rollno=int(input("Enter rollno whose name you want to display:"))
f=open("StudentDetails.dat","rb")
try:
while True:
rec=pickle.load(f)
if rec[0]==rollno:
print(rec[1])
found=1
break

except EOFError:
f.close()
if found==0:
print("Sorry..No record found")

Write()
Read()
Search()
Output:
Q9: Write a program to create a binary file with roll number, name and marks.
Input a roll number and update the marks.
Program:
import pickle
def Write():
f=open("Studentdetails.dat",'wb')
while True:
r=int(input("Enter Rollno: "))
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 recors:(Y/N) ")
if ch in "N/n":
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 rollno whose mark you want to update: "))

try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
um=int(input("Enter updated Marks: "))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()
Output:

Q10: Write a program to write a random number generator that generates


random numbers between 1 and 6 (simulates a dice).
Program:
import random
while True:
print("="*65)
print(" ********** ROLLING THE DICE ********* ")
print("="*65)
num=random.randint(1,6)
if num==6:
print("Hey...You got",num,"Congratulations")
elif num==1:
print("well tried...But you got ",num)
else:
print("You got ",num)
print(num)
ch=input("Roll Again ?(Y/N)")
if ch in 'Nn':
break
print("Thanks for Playing !!!!!!!!")

Output:
Q11: Write a program to Write a Python program to implement a stack using list.
Program:
stack=[]
def push():
element=input("Enter the element:")
stack.append(element)
print(stack)

def pop_element():
if not stack:
print("stack is empty!")
else:
e=stack.pop()
print("Removed element:",e)
print(stack)

while True:
print("Select the operation 1. Push 2.Pop 3.Quit")
choice=int(input())
if choice==1:
push()
elif choice==2:
pop_element()
elif choice==3:
break
else:
print("Enter the correct operation")

Output:

Q12: Create a CSV file by entering user-id and password, read and search the
password for given userid
Program
import csv
def write():
f=open("details.csv","w",newline='')
wo=csv.writer(f)
wo.writerow(["UserId","Password"])
while True:
u_id=input("Enter User_Id:")
pswd=input("Password: ")
data=[u_id,pswd]
wo.writerow(data)
ch=input("Do you want to enter more records (Y/N)")
if ch in 'Nn':
break
f.close()
def read():
f=open("details.csv","r")
ro=csv.reader(f)
for i in ro:
print(i)
f.close()

def search():
f=open("details.csv","r")
found=0
u=input("Enter user-id to search: ")
ro=csv.reader(f)
next(ro)
for i in ro:
if i[0]==u:
print(i[1])
found=1
f.close()
if found==0:
print("Record not found!!")
write()
read()
search()

MYSQL
Q13: Create a student table and insert data. Implement the following
SQL Commands in the student table:
 Alter table to add new attributes/Modify data type/ Drop
attribute.
 Update table to modify data ORDER BY to display data in
ascending /descending order.
 DELETE to remove tuple(s) GROUP BY and find the
MIN,MAX,SUM,COUNT and AVERAGE.
Queries:
a) create database class12
Command
mysql> create database class12;
Query OK, 1 row affected (0.03 sec)
mysql> use class12;
Database changed

b) Create table Student


Command
mysql> create table Student
-> (Rno int Primary Key,
-> Name varchar(10),
-> Gender varchar(8),
-> Marks int,
-> Scode varchar(5)
-> );
Query OK, 0 rows affected (0.62 sec)

c) To view the structure of table Student


Command
mysql> desc Student;

d) Inserting data in Student table


Command
e) Display all the records from Student
Command

f) Display the details of the students whose Scode is S101


Command

g) Display the name of the student who scored marks between 50 and 80
Command
h) Alter Table (Add Attributes ContactNo , Address to Student table)
Command

i) Alter Table (Drop Attribute ContactNo from Student table)


Command
j) Alter Table (Modify Data type of Marks to Decimal)
Command

k) Update Command (update table Student and set the address’ Sector 17’ for
Scode S101)
Command
l) ORDER By to display data in ascending / descending order

Command

m) DELETE to remove tuple(s)


Command
n) GROUP BY and find the min, max, sum, count and average
Command

Q14: Write a program to integrate SQL with Python by importing the MYSQL
module record of Employee and display the record.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='cityschool')
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()

while True:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT ")
s=int(input("Enter Choice: "))
if s==1:
e=int(input("Enter employee number:"))
n=input("Enter employee name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif s==2:
query="select * from employee"
cur.execute(query)
result=cur.fetchall()

for row in result:


print(row)
elif s==0:
con.close()
print("Bye !!")
break
else:
print("Invalid choice!!")

Output:

Q15 : Write a program to integrate SQL with Python by importing the MYSQL
Module to search an employee using empno and if present in table display
record, if not display appropriate method.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',database='company',password='
cityschool')
cur=con.cursor()
print("#"*40)
print("\n\n")
while True:
eno=int(input("Enter empno to display the details:"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found")
else:
for row in result:
print(row)
ch=input("Do you want to search more records (Y/N)")
if ch in 'Nn':
break

Output:
Q16: Write a program to integrate SQL with Python by importing the MYSQL
Module to Update the Salary of employee using the empno.
Program:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',database='company',p
assword='surya')
if con.is_connected():
print("Connected")
else:
print("Not Connected")

cur=con.cursor()
print("#"*10)
print("EMPLOYEE UPDATION FORM")
print("#"*10)
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to update:"))
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("Record found")
for row in result:
ch=input("Are you sure to update(Y):")
if ch.lower()=="y":
print("You can update only the salary")
try:
s=int(input("Enter new salary:"))
except:
s=row[3]
query="Update employee set salary={} where empno={}".format(s,eno)
cur.execute(query)
con.commit()
print("Record updated successfully")
ans=input("Update more(Y)")

Output:

You might also like