Professional Documents
Culture Documents
Q1. Write a program to accept two numbers from a user and add
them.
def sumtwo(x,y):
add=x+y
return add
num1=float(input("Enter the first number: "))
num2=float(input("Enter the second number: "))
sum=sumtwo(num1,num2)
print("Sum of the two entered numbers is",sum)
Q2. Write a program to calculate Simple Interest accepting values
from the user and having default values of rate and time.
def allop(x,y):
sum=x+y
sub=x-y
mul=x*y
div=x/y
pow=x**y
return sum,sub,mul,div,pow
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
a,b,c,d,e=allop(num1,num2)
print("Sum of the numbers is ",a)
print("Difference of the numbers is ",b)
print("Product of the numbers is ",c)
print("Division of the numbers is ",d)
print("Exponent of the numbers is ",e)
Q4. Write a program to print the sum of digits of a number using
functions.
def digSum(x):
sum=0
while (x!=0):
sum=sum+x%10
x=x//10
return sum
y=int(input("Enter the number whose sum of digits you want: "))
u=digSum(y)
print(u,"is the sum of the digits of the number.")
Q5. Write a program to check whether a number is prime or not using
functions.
def primenumber():
num=int(input("Enter the number: "))
if 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 neither a prime number nor a composite number.")
primenumber():
Q6. Write a program to check whether a given number is a
palindrome or not using functions.
def palindrome(x):
numx=x
rev=0
while(x>0):
dig=x%10
rev=rev*10+dig
x=x//10
if(rev==numx):
print("The number is a palindrome!")
else:
print("The number is not a palindrome!")
y=int(input("Enter the number: "))
palindrome(y)
Q7. Write a program to create a number game using the random
module.
import random
def numbergame():
print("Welcome to numbergame. You have 3 chances to guess a number from
1 and 10.")
n=0
x=random.randint(1, 10)
while n<3:
y=int(input("Enter the number: "))
if y==x:
print("Yay! You won. Congrats!")
break
else:
print("Try Again.")
n+=1
else:
print("You lost. Do you want to play again? y for yes, n for no.")
u=input("Enter your choice: ")
if u=='y':
numbergame()
else:
print("Thank you for playing numbergame. Have a good day!")
numbergame()
FILE HANDLING
1) Binary Files
Q8. Write a program to get student data (roll no, name and
marks) from user and write in on a binary file.
import pickle
student={}
file=open(r'Student.dat','wb')
perm="y"
while perm=="y":
rno=int(input("Enter roll number: "))
name=input("Enter name: ")
marks=float(input("Enter Marks: "))
student["RollNo"]=rno
student["Name"]=name
student["Marks"]=marks
pickle.dump(student,file)
perm=input("Do you want to enter more records? y/n")
file.close()
Q9. Write a program to read all the content written in the binary
file ‘student.dat’.
import pickle
file=open(r’Student.dat’,’rb’)
x={}
try:
while True:
x=pickle.load(file)
print(x)
except:
print("File read successfully.")
Q10. Write a program to read all the content in a file named
‘Employeee.dat’ and print the sum of salaries of entered post.
import pickle
def sumsalary(post):
file=open(r'Employeee.dat','rb')
sum=0
try:
while True:
x=pickle.load(file)
if x["Post"]==post:
sum+=x["Salary"]
except:
print("File read successfully.")
print(sum,'is the total sum of the salary of',post,'post')
post=input("Enter post: ")
sumsalary(post)
2) Text Files
Q11. Write a program to read a text file line by line and display
each word separated by a “#”.
file=open(r"Storyking.txt",'r')
y=' '
while y:
y=file.readline()
for i in y.split():
print(i,end='#')
print()
Q12. Write a program to add new words in the file
“Storyking.txt” without losing older data.
def appendstory(x):
file=open(r'Storyking.txt','a')
file.write(x)
print("Successfully added the words to the file.")
y=input("Enter the text you want to append: ")
appendstory(y)
Q13. Write a program to read a text file “Storyking.txt” and
display the count of vowels and consonants in the file.
def voco():
file=open(r'Storyking.txt','r')
countvowel=0
countconsonant=0
y=file.read()
for i in y:
if i in 'aeiouAEIOU':
countvowel+=1
elif i.isalpha() and i not in 'aeiouAEIOU':
countconsonant+=1
print(countvowel,'is the number of vowels in the file.')
print(countconsonant,'is the number of consonants in the file.')
voco()
3) CSV Files
import csv
file=open(r'Student1.csv','w')
x=csv.writer(file)
x.writerow(['Roll No','Name','Marks'])
y=int(input("Enter the no of records you want to enter: "))
for i in range(y):
print("Record no.",i+1)
rno=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=float(input("Enter marks: "))
record=[rno,name,marks]
x.writerow(record)
print("File created and records added succesfully.")
Q15. Write a program to display the records entered in the file
‘Student1.csv’.
import csv
file=open(r'Student2.csv','r')
reader1=csv.reader(file)
for i in reader1:
print(i)
PYTHON SQL CONNECTIVITY
Q.16 Write a program to ask the user and enter records in the table
studentsdata.
def inserting_values():
import mysql.connector
y=mysql.connector.connect(host='localhost',user='root',password='lavish2006',dat
abase='lavish_work')
x=y.cursor()
a=input("Enter name :")
b=int(input("Enter roll no: "))
c=int(input("Enter marks: "))
x.execute("insert into studentsdata values('{}',{},{})".format(a,b,c))
y.commit()
x=int(input("Enter how many values you want to enter: "))
for i in range(x):
inserting_values()
print("Values inserted successfully.")
Q17. Write a program to display the record of student with the
roll no entered by the user.
def display_values():
import mysql.connector
y=mysql.connector.connect(host='localhost',user='root',password='lavish2006',database=
'lavish_work')
x=y.cursor()
q=int(input("Enter the roll no which you wish to display data from: "))
a="select *from studentsdata where roll_no={}"
x.execute(a.format(q))
result=x.fetchone()
print("Name Roll_No Marks")
for i in result:
print(i,end=" ")
def display_all():
import mysql.connector
y=mysql.connector.connect(host='localhost',user='root',password='lavish2006',d
atabase='lavish_work')
x=y.cursor()
a="select *from studentsdata"
x.execute(a)
result=x.fetchall()
print("Name Roll_No Marks")
for i in result:
print(i,end=" ")
print("Select 1 for displaying all values and 2 for particular value with roll no.")
x=int(input("Enter your choice: "))
if x==1:
display_all()
elif x==2:
display_values()
Q18. Write a program to update the marks in the table
studentsvalues by roll no asked from user.
def update_values():
import mysql.connector
y=mysql.connector.connect(host='localhost',user='root',password='lavish2006',d
atabase='lavish_work')
x=y.cursor()
i=int(input("Enter new marks: "))
a="update studentsdata set marks={} where roll_no={}"
x.execute(a.format(i,j))
y.commit()
print("Value update successfully.")
j=int(input("Enter the roll no of the student: "))
update_values()
Q19. Write a program to delete the values of the selected student
by his roll no.
def delete_values():
import mysql.connector
y=mysql.connector.connect(host='localhost',user='root',password='lavish2006',d
atabase='lavish_work')
x=y.cursor()
a="delete from studentsdata where roll_no={}"
x.execute(a.format(u))
y.commit()
print("Value deleted successfully.")
u=int(input("Enter the roll no of the student: "))
delete_values()
STACKS
Q20.Write a python program to check whether a string is a
palindrome or not using stack.
stack = []
top = -1
def push(ele):
global top
top += 1
stack[top] = ele
def pop():
global top
ele = stack[top]
top -= 1
return ele
def isPalindrome(string):
global stack
length = len(string)
stack = ['0'] * (length + 1)
mid = length // 2
i=0
while i < mid:
push(string[i])
i += 1
if length % 2 != 0:
i += 1
while i < length:
ele = pop()
if ele != string[i]:
return False
i += 1
return True
string = input("Enter string to check:")
if isPalindrome(string):
print("Yes, the string is a palindrome")
else:
print("No, the string is not a palindrome")
MYSQL QUERIES
6) Display the list of movies which are going to release in February, 2022.
Select movie_name from movies
where releasedate>’2022-01-31’ and releasedate<‘2022-03-01’;
2.Consider the given table patient and Write following queries:
13) Display avg price of items for each dealer as per dcode from stock
which average price is more than 5.
Select dcode, avg(unitprice) from sales
group by dcode having avg(unitprice)>5;
3. Refer to the Movie table in the first question, and the given
table, join them and answer the following questions.
14) Display the name of movies, heroes and their ages by ascending order.
Select movie_name, hero_name, hero_age from movies, moviehero
Where movies.movie_id=moviehero.m_id
Order by hero_age;
15) Display the name of the movies where the hero’s age is less than 40.
Select movie_name, hero_age from movies, moviehero
Where movies.movie_id=moviehero.m_id and hero_age<40;