Bhavya

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

Report File

Name:- Bhavya Karamchandani


Class:- 12 Science B
Roll no. 05
Q1. Write a program in python to check a number whether it is prime or not.
num=int(input("Enter the number: "))
for i in range(2,num):
if num%i==0:
print(num, "is not prime number")
break;
else:
print(num,"is prime number")

Output

Q2. Write a program to check a number whether it is palindrome or not.


num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
Output

Q3. Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a character of a
value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False
Output

Q4. Write a program to find factorial of a number.


def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num=int(input("enter the number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of ",num," is ", factorial(num))

Output

Q5. Write a program to display those string which are starting with ‘A’ from the given list.
string_list = ['Example', 'Altamas', 'Apple']
for word in string_list:
if 'A' in word:
print(word)
Output
Q6. Write a program to show functionality of a basic calculator using functions.
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:

choice = input("Enter choice(1/2/3/4): ")

if choice in ('1', '2', '3', '4'):


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

next_calculation = input("Let's do next calculation? (yes/no): ")


if next_calculation == "no":
break
else:
print("Invalid Input")
Output

Q7. Write a function SwapNumbers( ) to swap two numbers and display the numbers before
swapping and after swapping.
def SwapNumbers(x,y):
a, b = y, x
print("After Swap:")
print("Num1: ", a)
print("Num2: ", b)
Num1=int(input("Enter Number-1: "))
Num2=int(input("Enter Number-2: "))
print("Before Swap: ")
print("Num1: ", Num1)
print("Num2: ", Num2)
SwapNumbers(Num1, Num2)
Output

Q8. Write a program to find the sum of all elements of a list using recursion.
def SumAll(L):
n=len(L)
if n==1:
return L[0]
else:
return L[0]+SumAll(L[1:])
LS=eval(input("Enter the elements of list: "))
total=SumAll(LS)
print("Sum of all elements is: ", total)
Output

Q9. Write a program to print fibonacci series using recursion.


def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))
num=int(input("How many terms you want to display: "))
for i in range(num):
print(fibonacci(i)," ", end=" ")
Output

Q10. Write a program to generate random numbers between 1 to 6 and check whether a user
won a lottery or not.
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)
Output

Q11. Write a program to count the number of vowels present in a text file.
Text file

Code
vowels=0
with open(r'Hotel.txt','r') as file:
data=file.read
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
for alpha in file.read():
if alpha in vowels_list:
vowels += 1
print(vowels)
Output

Q12. Write a program to count the number of words in a file.


Text File
Code
# creating variable to store the
# number of words
number_of_words = 0

# Opening our text file in read only


# mode using the open() function
with open(r'ABC.txt','r') as file:

# Reading the content of the file


# using the read() function and storing
# them in a new variable
data = file.read()

# Splitting the data into separate lines


# using the split() function
lines = data.split()

# Adding the length of the


# lines in our number_of_words
# variable
number_of_words += len(lines)

# Printing total number of words


print(number_of_words)
Output

Q13. Write a python program to read student data from a binary file.
import pickle
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
file.close( )
Output

Q14. Write a python program to write student data in a binary file.


import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")
pickle.dump(list, file)
file.close( )
Output

Q15. Write a python program to delete student data from a binary file.
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )
Output

Q16. Write a program to perform read operation with .csv file.


import csv
with open('data.csv') as f:
reader=csv.reader(f)
for i in reader:
print(i)
f.close
Output

Q17. 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

Q18. Write a program for bubble sort.


L=eval(input("Enter the elements:"))
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
t=L[i]
L[i]=L[i+1]
L[i+1]=t
print("The sorted list is : ", L)
Output

Q19. Write a program to perform the following operations on data in the database: Create, Insert,
Fetch, Update and delete the data.
Q20. In MySql, Create a database named SGNPS, under this database create table named
STUDENT with admno,name,class,sec,rno,address.Insert two rows of data.
Q21. Write a program to read data from a text file info.TXT, and display each word with number
of vowels, lines and consonants.
Text File
Code
vowels=0
with open(r'ABC.txt','r') as file:
data=file.read
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
for alpha in file.read():
if alpha in vowels_list:
vowels += 1
print('Number of vowels:',vowels)

consonants=0
with open(r'ABC.txt','r') as file:
data=file.read
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
for alpha in file.read():
if alpha not in vowels_list and alpha != "\n":
consonants += 1
print('Number of consonants:',consonants)

lines=0
with open(r'ABC.txt','r') as file:
lines=len(file.readlines())
print('Number of lines:',lines)

Output
Q22. Write a program to read data from a text file value.TXT, and display word by word.
with open('Hotel.txt','r') as file:

# reading each line


for line in file:

# reading each word


for word in line.split():

# displaying the words


print(word)
Output

Q23. Write a program to perform write operation with .csv file.


import csv
with open('data.csv','w') as f:
writer=csv.writer(f)
writer.writerow(['Analyst','AdityaMehra','Pune'])
writer.writerow(['Programmer','KaranSeghal','Nashik'])
writer.writerow(['Manager','KritiSharma','Mumbai'])
print("Data successfully add")
f.close
Output

Q24. Write a menu based program to perform the operation on queue in python.
def Enqueue(n):
L.append(n)
if len(L)==1:
f=r=L[0]
else:
r=L[len(L)-1]
f=L[0]
def Dequeue():
if len(L)==0:
print("Queue is empty")
elif len(L)==1:
print("Deleted element is: ", L.pop(0))
print("Now queue is empty")
else:
print("Deleted element is: ", L.pop(0))
def Display():
if len(L)==0:
print("Queue is empty")
else:
print(L)
r=L[len(L)-1]
f=L[0]
print("Front is : ", f)
print("Rear is : ", r)
def size():
print("Size of queue is: ",len(L))
def FrontRear():
if len(L)==0:
print("Queue is empty")
else:
r=L[len(L)-1]
f=L[0]
print("Front is : ", f)
print("Rear is : ", r)

L =[]
print("MENU BASED QUEUE")
cd=True
while cd:
print(" 1. ENQUEUE ")
print(" 2. DEQUEUE ")
print(" 3. Display ")
print(" 4. Size of Queue ")
print(" 5. Value at Front and rear ")
choice=int(input("Enter your choice (1-5) : "))
if choice==1:
val=input("Enter the element: ")
Enqueue(val)
elif choice==2:
Dequeue( )
elif choice==3:
Display( )
elif choice==4:
size( )
elif choice==5:
FrontRear()
else:
print("You entered wrong choice ")
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
cd=True
else:
cd=False
Output

Q25. 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==5:
Top( )
else:
print("You enetered wrong choice ")
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False
Output
Q26.
1. To write a Python Program to integrate MYSQL with Python to create Database and Table
to store the details of employees.
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$')
cursor=con.cursor()
try:
cursor.execute("create database detailsDB")
db = cursor.execute("show databases")
except:
con.rollback()
for i in cursor:
print(i)
con.close

import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database='de
tailsDB')
cursor=con.cursor()
try:
db=cursor.execute("create table Emp(EmpID integer,Name varchar(30),Address varchar(20),Post
varchar(25),Salary integer)")
except:
con.rollback()
Con.close
Output

2. Also alter the table.


import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database='de
tailsDB')
cursor=con.cursor()
try:
cursor.execute("alter table Emp ad Age integer")
except:
con.rollback()
con.close()
Output

Q27. To write a Python Program to integrate MYSQL with Python by inserting records to Emp
table and display the records.
import mysql.connector
db =
mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database='detail
sDB')
cursor = db.cursor()

sql = "INSERT INTO Emp (EmpID, Name, Address, Post, Salary, Age) VALUES (%s, %s, %s, %s,
%s, %s)"
values = [(1101, "Aryan", "Anand", "Programmer", 125000, 24),
(1102, "Bhavin", "Ahembadad", "Analyst", 150000, 25),
(1103, "Rajat", "Surat", "Manager", 200000, 28)]

cursor.executemany(sql, values)
db.commit()
print(cursor.rowcount, "record inserted.")
Output
Q28. To write a Python Program to integrate MYSQL with Python to search an Employee using
EMPID and display the record if present in already existing table EMP, if not display the
appropriate message.
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database=
'detailsDB')
cursor=con.cursor()
try:
cursor.execute("Select * from Emp where EmpID=1102")
display = cursor.fetchone()
print(display)
except:
con.rollback()
con.close()
Output

Q29. To write a Python Program to integrate MYSQL with Python to search an Employee using
EMPID and update the Salary of an employee if present in already existing table EMP, if not
display the appropriate message.
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database='de
tailsDB')
cursor=con.cursor()
statement ="UPDATE Emp SET Salary = 175000 WHERE EmpID=1102"
try:
cursor.execute(statement)
con.commit()
except:
con.rollback
con.close()
Output
Q30. To write a Python Program to integrate MYSQL with Python to delete a record.
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='$#ABTabt123#$',database='de
tailsDB')
cursor=con.cursor()
statement ="DELETE FROM Emp where Salary =200000"
try:
cursor.execute(statement)
con.commit()
except:
con.rollback
con.close()
Output

You might also like