0% found this document useful (0 votes)
16 views43 pages

Rishabh Programss

Uploaded by

salonijayant27
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)
16 views43 pages

Rishabh Programss

Uploaded by

salonijayant27
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/ 43

1

CERTIFICATE
This is To certify that this is to certify
that RISHABH KUMAR of 12th of CPS
International School has completed his
report file under my supervision he has
completed the report file work
independently and has shown utmost
sincerity in completion of this file.
This report file fully implements all the
topics and concept done in Python And
MySQL covered in class 11th and 12th
as per the CBSE syllabus of computer
science subject.
I certify that this practical file is up to
my expectation and as per guidelines
issued by CBSE.

DEEPTI AGGARWAL MRS.


MEENAKSHI
2

PGT COMPUTER SCIENCE PADHY


(PRINCIPAL)

ACKNOWLEDGEMENT
I would like to take this opportunity to
extend my sincere gratitude and
appreciation to my computer lab
teacher Mrs. DEEPTI AGGARWAL for
providing guidance and support
throughout the process of completing
my computer project for school.
I am also thankful to my principal Mrs.
MEENAKSHI PADHY for allowing me the
opportunity to explore and work on this
project in the school environment.
Additionally, I would like to express my
heartfelt thanks to my family for their
unwavering support and
encouragement during the completion
of this project.
3

RISHABH KUMAR
XII A (SCIENCE)

INDEX
PARTS TITTLE
1. PROGRAM 1
PROGRAM 2
PROGRAM 3
PROGRAM 4
PROGRAM 5
PROGRAM 6
PROGRAM 7
PROGRAM 8
PROGRAM 9
PROGRAM 10
PROGRAM 11
PROGRAM 12
PROGRAM 13
PROGRAM 14
PROGRAM 15
2 QUESTION 1
QUESTION 2
QUESTION 3
QUESTION 4
QUESTION 5
4

3 QUESTION 1
QUESTION 2
QUESTION 3
QUESTION 4

Program 1 : write the definition of user define function


push3_5(N)which accept a list of intgerers in a parameter
N and pushes all those integers which are divisible by 3 or
divisible by 5 from the list N intoa list named only3_5 :

def Push3_5(N):
"""
This function accepts a list of integers N,
and pushes all integers divisible by 3 or 5 into a list named Only3_5.
Args:
N (list): A list of integers.
Returns:
list: A list of integers divisible by 3 or 5.
"""
Only3_5 = []
for num in N:
if num % 3 == 0 or num % 5 == 0:
Only3_5.append(num)
return Only3_5
numbers = [1,2,3,4,5,6,7,8,9,10,11,1,12]
result = Push3_5(numbers)
print(result)

output:
RESTART:
C:/Users/rishabh/AppData/Local/Programs/Python/Python311/python
1.py
[3, 5, 6, 9, 10, 12]
5
6

PROGRAM 2 : Write a program in Python to input 5 integers


into a list named NUM. The program should then use the
function Push3 51) to create the stack of the list Only3_5.
Thereafter pop each integer from the list Only3 5 and display
the popped value. When the list is empty, display the message
"StackEmpty". For example:If the integers input into the list
NUM are: [10, 6, 14, 18, 30] Then the stack Only3 5 should
store(10, 6, 18, 30) And the output should be displayed as 30 18
6 10 StackEmpty:
def Push3_5(NUM):

# This function will filter the integers from NUM that are either 3 or 5

Only3_5 = []

for num in NUM:

if num == 3 or num == 5:

Only3_5.append(num)

return Only3_5

# Input: taking 5 integers and storing them in the list NUM

NUM = []

for i in range(5):

num = int(input("Enter an integer: "))

NUM.append(num)

# Create the stack Only3_5 using the Push3_5 function

Only3_5 = Push3_5(NUM)

# Display and pop elements from Only3_5 stack

while Only3_5:

# Pop the last element (stack behavior)

popped_value = Only3_5.pop()

print(popped_value, end=" ")

# If the stack is empty, print "StackEmpty"

if not Only3_5:

print("\nStackEmpty")

OUTPUT:
Enter an integer: 10,6,14,18,30RESTART:
C:/Users//AppData/Local/Programs/Python/Python311/ 1.py
[3, 5, 6, 9, 10, 12]
7

PROGRAM 3 : Write the definition of a function Sum3(L) in


Python, which accepts a list L of integers and displays the sum
of all such integers from the list L which end with the digit 3.For
example, if the list L is passed(123, 10, 13, 15, 23]then the
function should display the sum of 123, 13, 23, i.e. 159 as
Follows:Sum of integers ending with digit 3 = 159.

def Sum3(L):
# Initialize the sum variable to 0
total_sum = 0
# Iterate through each integer in the list
for num in L:
# Check if the last digit of num is 3
if num % 10 == 3:
total_sum += num # Add num to the total sum
# Display the sum
print(f"Sum of integers ending with digit 3 =
{total_sum}")
# Example usage:
Sum3([123, 10, 13, 15, 23])

OUTPUT:
RESTART:
C:/Users//AppData/Local/Programs/Python/Python311/
Sum of integers ending with digit 3 = 159
8

PROGRAM 4 : Write the definition of a function Count_Line()


in Python, which should read each line of a text file
"SHIVAJI.TXT" and count total number of lines present in text
file. For example, if the content of the file "SHIVAJI.TXT" is as
follows:Shivaji was born in the family of Bhonsle. He was
devoted to his mother Jijabai.India at that time was under
Muslim rule.The function should read the file content and
display the output as follows:

def Count_Line():
# Initialize a counter to keep track of the number of
lines
line_count = 0
# Open the file "SHIVAJI.TXT" in read mode
try:
with open("SHIVAJI.TXT", "r") as file:
# Loop through each line in the file
for line in file:
# Increment the line count for each line read
line_count += 1
# Display the total number of lines
print(f"Total number of lines: {line_count}")
except FileNotFoundError:
print("The file 'SHIVAJI.TXT' was not found.")
#EXAMPLE: Shivaji was born in the family of Bhonsle.He
was devoted to his mother Jijabai.India at that time was
under Muslim rule.
OUTPUT:
C:\Users\\AppData\Local\Programs\Python\Python311\
PYTHON 3.py
Total number of lines : 3
9

PROGRAM 5: Write a python program to read a file


named "story.txt", count and print total lines
starting with vowels in the file.
Filepath = 'story.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if(line[0] in vowels):
#print(line)
print("Line {}: {}".format(cnt, line.strip()))
cnt=cnt+1
line = fp.readline()
OUTPUT:
RESTART:C:/Users/Gunjan/AppData/Local/Programs/Python/
Python31/ PYTON 4.py
LINE 1 : AMIT
Line 2: owl
Line 3 : eat apple a day,
10

Program 6 : Write a python program to read a file


named "xyz.txt", count and print total words
starting with "a" or "A" in the file.
def count_lines_starting_with_k(file_path):
count = 0
with open(file_path, 'r') as file:
for line in file:
if line.startswith('K'):
count += 1
return count

# Example usage
file_path = 'your_file.txt' # Replace with your file path
result = count_lines_starting_with_k(file_path)
print(f"Number of lines starting with 'K': {result}")

OUTPUT:
RESTART: C:\Users\\AppData\Local\Programs\Python\
Python311\ python4.py
Number of lines starting with 'K': 4

program 7: Write a python program to read a file named


"article.txt", count and print alphabets in the file.

# Open the file in read mode


11

with open("article.txt", "r") as file:


# Read the entire content of the file
content = file.read()
# Initialize a counter for alphabetic characters
alphabet_count = 0
# Iterate through each character in the content
for char in content:
# Check if the character is an alphabet (ignores case)
if char.isalpha():
alphabet_count +=
# Print the total count of alphabets
print(f"Total alphabets in the file: {alphabet_count}
Example

This is a sample article.


It contains multiple lines of text.

Output :
RESTART:C:\Users\Gunjan\AppData\Local\Programs\
Python\Python311\rishabh python4.py
Total alphabets in the file: 56
12

PROGRAM 8 : Write a python program to maintain


book details like book code, book title and price
using stacks data structures? (Implement push(),
pop() and traverse() functions""
class Book:

def _init_(self, book_code, book_title, price):

self.book_code = book_code

self.book_title = book_title

self.price = price

def _str_(self):

return f"Book Code: {self.book_code}, Title: {self.book_title}, Price:


{self.price}"

class BookStack:

def _init_(self):

self.stack = []

# Push a book onto the stack

def push(self, book):

self.stack.append(book)

# Pop a book from the stack

def pop(self):

if len(self.stack) == 0:

print("Stack is empty! No book to pop.")

else:

return self.stack.pop()

# Traverse and print all books in the stack

def traverse(self):

if len(self.stack) == 0:

print("Stack is empty! No books to display.")

else:

print("Books in stack:")

for book in self.stack:

print(book)

# Driver code to test the stack


13

if _name_ == "_main_":

book_stack = BookStack()

# Adding books to the stack

book_stack.push(Book("B001", "Python Programming", 599.99))

book_stack.push(Book("B002", "Data Structures and Algorithms", 499.99))

book_stack.push(Book("B003", "Machine Learning Basics", 699.99))

# Traverse the stack to display all books

book_stack.traverse()

# Pop a book from the stack

print("\nPopping a book from the stack:")

popped_book = book_stack.pop()

print(f"Popped: {popped_book}")

# Traverse the stack again after popping

print("\nBooks in stack after popping:")

book_stack.traverse()

# Pop all books from the stack

print("\nPopping all books:")

while True:

popped_book = book_stack.pop()

if popped_book is None:

break

print(f"Popped: {popped_book}")

OUTPUT:

*Books in stack:

Book Code: B001, Title: Python Programming, Price: 599.99

Book Code: B002, Title: Data Structures and Algorithms, Price: 499.99

Book Code: B003, Title: Machine Learning Basics, Price: 699.99

*Popping a book from the stack:

Popped: Book Code: B003, Title: Machine Learning Basics, Price: 699.99

Books in stack after popping:

Book Code: B001, Title: Python Programming, Price: 599.99

Book Code: B002, Title: Data Structures and Algorithms, Price: 499.99

*Popping all books:


14

Popped: Book Code: B002, Title: Data Structures and Algorithms, Price: 499.9

PROGRAM 9 :Write a python program to display fibonacci


sequence using recursion.

def fibonacci(n):

if n <= 0:

return "Invalid input! Please enter a positive integer."

elif n == 1:

return 0

elif n == 2:

return 1

else:

return fibonacci(n - 1) + fibonacci(n - 2)

# Function to display the Fibonacci sequence

def display_fibonacci_sequence(count):

print("Fibonacci Sequence:")

for i in range(1, count + 1):

print(fibonacci(i), end=" ")

# Get user input for the number of terms

try:

n_terms = int(input("Enter the number of terms: "))

if n_terms > 0:

display_fibonacci_sequence(n_terms)

else:

print("Please enter a positive integer.")

except ValueError:

print("Invalid input! Please enter an integer.")

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\
rishABH PYTHON 2.py

Enter the number of terms: 7

Fibonacci Sequence:

0 1 1 2 3 5 8
15

PROGRAM 10: Write a Python program to take input for a number


check if the entered number is Armstrong or not .

def is_armstrong(number):

num_str = str(number)

num_digits = len(num_str)

sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)

return number == sum_of_powers

# Take input from the user

try:

num = int(input("Enter a number: "))

if num >= 0: # Armstrong numbers are non-negative

if is_armstrong(num):

print(f"{num} is an Armstrong number.")

else:

print(f"{num} is not an Armstrong number.")

else:

print("Please enter a non-negative integer.")

except ValueError:

print("Invalid input! Please enter an integer.")

OUTPUT:

RESTART: C:\Users\\AppData\Local\Programs\Python\Python311\
rishABH PYTHON 2.py

Enter a number: 153

153 is an Armstrong number

Enter a number: -5

Please enter a non-negative integer.


16

PROGRAM 11: Write a python program to take input for 2 numbers


and and operator(+,-,*,/) based on the operator calculate and print
the result .

def calculate(num1, num2, operator):

if operator == '+':

return num1 + num2

elif operator == '-':

return num1 - num2

elif operator == '*':

return num1 * num2

elif operator == '/':

if num2 != 0:

return num1 / num2

else:

return "Division by zero is not allowed!"

else:

return "Invalid operator!"

# Take input for numbers and operator

try:

number1 = float(input("Enter the first number: "))

number2 = float(input("Enter the second number: "))

operator = input("Enter an operator (+, -, *, /): ").strip()

# Perform the calculation and print the result

result = calculate(number1, number2, operator)

print(f"Result: {result}")

except ValueError:

print("Invalid input! Please enter numeric values for numbers.")

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py

Enter the first number: 10

Enter the second number: 5

Enter an operator (+, -, *, /): +

Result: 15.0
17

PROGRAM:12 Write a Python program to take input for 3 numbers


check and print the largest name.

# Function to find the largest number

def find_largest(num1, num2, num3):

if num1 >= num2 and num1 >= num3:

return num1

elif num2 >= num1 and num2 >= num3:

return num2

else:

return num3

# Take input for three numbers

try:

number1 = float(input("Enter the first number: "))

number2 = float(input("Enter the second number: "))

number3 = float(input("Enter the third number: "))

# Find and print the largest number

largest = find_largest(number1, number2, number3)

print(f"The largest number is: {largest}")

except ValueError:

print("Invalid input! Please enter numeric values.")

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\
rishABH PYTHON 2.py

Enter the first number: 12

Enter the second number: 45

Enter the third number: 23

The largest number is: 45.0


18

PROGRAM 13: Read a text file and display the number of vowels/
consonants /uppercase/ lowercase characters in the file.

def analyze_file(filename):

try:

with open(filename, 'r') as file:

text = file.read()

vowels = "aeiouAEIOU"

vowel_count = 0

consonant_count = 0

uppercase_count = 0

lowercase_count = 0

for char in text:

if char.isalpha():

if char in vowels:

vowel_count += 1

else:

consonant_count += 1

if char.isupper():

uppercase_count += 1

elif char.islower():

lowercase_count += 1

print("File Analysis:")

print(f"Vowels: {vowel_count}")

print(f"Consonants: {consonant_count}")

print(f"Uppercase characters: {uppercase_count}")

print(f"Lowercase characters: {lowercase_count}")

except FileNotFoundError:

print(f"The file '{filename}' does not exist.")

except Exception as e:

print(f"An error occurred: {e}")

# Input the file name from the user

filename = input("Enter the filename (with extension): ")

analyze_file(filename)
19

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py

Vowels: 1134

Consonants: 2356

Uppercase characters: 3789

Lowercase characters: 3689


20

PROGRAM 14: Write a program to write data in a csv file


student.csv( it must be have at least 4 fields like id ,username,
account number, balance)

import csv

def write_to_csv(filename):

# Define the CSV header

fields = ['ID', 'Username', 'Account Number', 'Balance']

# Collect data to write

records = []

print("Enter student details. Type 'stop' to finish entering data.")

while True:

# Take input from the user

student_id = input("Enter ID: ")

if student_id.lower() == 'stop':

break

username = input("Enter Username: ")

account_number = input("Enter Account Number: ")

balance = input("Enter Balance: ")

# Append the data as a dictionary

records.append({

'ID': student_id,

'Username': username,

'Account Number': account_number,

'Balance': balance })

# Write to CSV file

try:

with open(filename, mode='w', newline='') as file:

writer = csv.DictWriter(file, fieldnames=fields)

writer.writeheader()

writer.writerows(records)

print(f"Data successfully written to {filename}")

except Exception as e:

print(f"An error occurred while writing to the file: {e}")

# Specify the filename


21

filename = 'student.csv'

write_to_csv(filename)

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py

Enter student details. Type 'stop' to finish entering data.

Enter ID: 101

Enter Username: Alice

Enter Account Number: 12345678

Enter Balance: 5000

Enter ID: 102

Enter Username: Bob

Enter Account Number: 87654321

Enter Balance: 7500

Enter ID: stop

ID,Username,Account Number,Balance

101,Alice,12345678,5000

102,Bob,87654321,7500
22

PROGRAM 15: Write a menu driven python program to implement


stack operation.

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

print(f"{item} pushed to stack.")

def pop(self):

if not self.is_empty():

item = self.stack.pop()

print(f"{item} popped from stack.")

else:

print("Stack is empty. Cannot pop.")

def peek(self):

if not self.is_empty():

print(f"Top element is: {self.stack[-1]}")

else:

print("Stack is empty. No top element.")

def display(self):

if not self.is_empty():

print("Stack elements are:")

for element in reversed(self.stack):

print(element)

else:

print("Stack is empty.")

def is_empty(self):

return len(self.stack) == 0

def menu():

print("\nStack Operations Menu:")

print("1. Push")

print("2. Pop")
23

print("3. Peek")

print("4. Display")

print("5. Exit")

# Main program

stack = Stack()

while True:

menu()

try:

choice = int(input("Enter your choice (1-5): "))

if choice == 1:

element = input("Enter the element to push: ")

stack.push(element)

elif choice == 2:

stack.pop()

elif choice == 3:

stack.peek()

elif choice == 4:

stack.display()

elif choice == 5:

print("Exiting program. Goodbye!")

break

else:

print("Invalid choice! Please select between 1 and 5.")

except ValueError:

print("Invalid input! Please enter a valid choice.")

OUTPUT:

RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py

Stack Operations Menu:

1. Push

2. Pop

3. Peek

4. Display
24

5. Exit

Enter your choice (1-5): 1

Enter the element to push: 10

10 pushed to stack.

Stack Operations Menu:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice (1-5): 1

Enter the element to push: 20

20 pushed to stack.

Stack Operations Menu:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice (1-5): 4

Stack elements are:

20

10

Stack Operations Menu:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice (1-5): 2

20 popped from stack.


25

Stack Operations Menu:

1. Push

2. Pop

3. Peek

4. Display

5. Exit

Enter your choice (1-5): 5

Exiting program. Goodbye!


26

PART – 2
DATA STRUCTURE AND SQL QUERIES .
QUESTION 1 : Consider the following MOVIE table write the SQL
queries based on it,

ID Movie Type Rdate Cost Revenue


M001 Dahek Action 2023/01/2 1245 1300
6
M002 Attack Action 2023/01/2 1120 1250
8
M003 Govinda name Thriller 2023/02/0 250 300
mera 1
M004 Badhai ho Drama 2023/02/0 720 68
4
M005 Shabash mithu Biograph 2023/02/0 1000 800
y 4
M006 gehraiyaan romance 2023/02/1 150 120
1

a) display all information from movie

b) display the type of movie.

c) display ID, movie cost and revenue by the movies. Calculate the profit
Using cost and revenue.

d) display ID, movie and cost for all movies with cost greater than 150 and
less than 1000.

e) display the movie of type action and romance.

f) display the list of movies which are going to release in February, 2023

ANSWERS:

ANS (A):

ANS(B):
27

ANS(C):

ANS(D)

ANS(E)

ANS(F)
28

QUESTION 2
PID PNAME AGE DEPARTMEN DATE OF CHARGE GENDER
T ADM S
1 KARAN 34 CARDIAC 2022-12- 550.00 M
02
2 MUKTA 15 WOMEN 2022-11- 2640.00 F
20
3 HARSHIT 22 MEN 2022-10- 2750.00 M
19
4 SUMAN 15 WOMEN 2022-08- 3080.00 F
11
5 AMIT 34 ORTHOPEDI 2022-11- 880.00 M
C 11
6 ALKA 41 CARDIAC 2022-05- 2069.00 F
20
7 RAKESH 42 MEN 2022-06- 1430.00 M
18

8 NIKITA 15 WOMEN 2022-07- 3190.0 F


06 0
9 SASHI 32 ORTHOPEDI NULL NULL NULL
C
10 AKASH 25 CARDIAC 2022-05- 3500.0 M
20 0

A) display the total charges of patients admitted in the month of


november.
B) Display the eldest patient with name and age,
C) Count th unique departments.
D) Display an average charge.

ANS(A)

ANS(B)

ANS(C)
29

ANS(D)
30

QUESTION 3
Q: Suppose your school management has decided to conduct
cricket matches between students of clas XI and class XII.Students
of each class are asked to join any one of the four teams – team
titan,team rockers,team magnet and team huricane.during summer
vacations , various matches will be conducted between these
teams.help your sports teacher to do the following:

A)create a database “sports”.

B)create a table “TEAM” with following considerations:

i) It should have a column teamID for storing an integer value between


1 and 9 ,which refers to unique identification of a team.

ii)Each teamID should have its associated name (team name) which
should be a string of length not less than 10 characters.

iii) using table level constraint,make TeamID as the primary key.

C)show the structure of the table TEAM using a sql statement.

D)As per the prefrences of the students four teams were formed as given
below , insert these four rows in TEM table.

i) ROW 1 :(1,RED)

ii)ROW 2:(2,GREEN)

iii)ROW 3:(3,YELLOW)

iv)ROW 4:(4,BLUE)

E) Show the contents of the table team using a dml statement.


F) Now Createanother tableMatch_Details and insert data shown blow
choose appropriate data types and constraints for each attribute .

matchI matchdat firstteami secondteam firstteamsco seconteamsco


D e d id re re
M1 2021/12/2 1 2 107 93
0
M2 2021/12/2 3 4 156 158
1
M3 2021/12/2 1 3 86 81
2
M4 2021/12/2 2 4 65 67
3
M5 2021/12/2 1 4 52 88
4
M6 2021/12/2 2 3 97 68
5

ANWERS:
31
32

QUESTION 4:
Q: Write the following queries:

a)display th match ID,teamid,teamscore , who with tem name.

b)Display the matchID,teamname,and second teamscorebetween 100 and 160.

c)Display the matchid,teamnamesalong with matchdates,

d)Display unique team names.

e) Display matchid and matchdateplayed by YELLOW and BLUE.

ANWERS:
33

QUESTION 5:
Q - Consider the following table (table name: stock) and write the queries:

Itemno. item dcode qty unitprice Stockdate


S005 Ballpen 102 100 10 2018/04/22
S003 Gellpen 101 150 15 2018/03/18
S002 Pencil 102 125 5 2018/02/25
S006 Eraser 101 200 3 2018/01/12
S001 Sahrpener 103 10 5 2018/06/11
S004 Compass 102 60 35 2018/05/10
S009 A4 papers 102 160 5 2018/07/17

a) display all the items in the ascending order of stock date.


b) Display maximum price of items for each dealer individually as per decode from
stock.
c) Display all the items in descending order of item names.
d) Display average price of items for each dealer individually as per decode from
stock which average prices more than 5.
e) Display the sum of quantity of for each decode.

ANWERS:

(A)

(B)
34

(C)

(D)

(E)
35

PART – 3
PYTHON DATABASE
CONNECTIVITY
QUESTION 1: Write a MySQL connectivity program in Python to a create a
database school b .create a table student with specification-Roll number
integer, St name character (10) in MySQL and perform the following
operations:

i) insert 2 records in it.


ii) Display the contents of the table.

import mysql.connector

mydb=mysql.connector.connect(host = "localhost", user = "root", password = "root")

mycursor mydb.cursor()

mycursor.execute("CREATE DATABASE school")

mycursor.execute("USE school")

mycursor.execute("CREATE TABLE students (roll_no INTEGER, stname VARCHAR(10))")

mycursor.execute("INSERT INTO students VALUES (1, 'Aman") (3. Ankit")")

mydb.commit()

mycursor.execute("SELECT FROM students")

value mycursor.fetchall()

for i in value:

print(f'Roll no: (1[0]), Student Name: (i[1])")

RESULTS:

(I)

(II)
36
37

QUESTION 2:
Q- Perform all the operations with reference to table “students” through MySQL
connectivity. (insert, update, delete):

import mysql.connector

mydb=mysql.connector.connect(host = "localhost", user "root", password = "root",


database="school")

mycursor mydb.cursor()

def main()

while True:

print("1. Insertion")

print("2. Update")

print("3. Delete")

print("4. Exit")

try:

choose = int(input("Input: "))

except (ValueError, TypeError)

continue

if choose == 1:

try:

roll_no= int(input("Roll no: "))

name= input("Name(10 Character)")

except (ValueError, TypeError):

continue

data (roll_no, name)

mycursor.execute("INSERT INTO students VALUES (%s%s)" data)

mydb.commit()

elif choose 2:

try:

old_roll_no = int(input("Old Roll no.))

roll_no= int(input("New Roll no."))

name= input("New Name:")

except (ValueError, TypeError)

continue

data (roll_no,name.old_roll_no)

mycursor.execute("UPDATE students SET roll_no = %s,stname=%s WHERE roll_no=


38

%s)" data)

mydb.commit()

elif choose ==3

try:

roll_no= int(input("Roll no: "))

except (ValueError, TypeError):

continue

data = ((roll_no).)

mycursor.execute("DELETE FROM students WHERE roll_no=%s", data)

mydb.commit()

elif choose== 4

break

else:

continue

if_name_==”_main_”:

RESULT:
39

QUESTION 3:
40

Q- Write a menu- driven program to store data into a MySQL table customer as
following :

(A) add customer details

(b)update customer details

(C). delete customer details.

(D)display all customer details.

Import mysql.connector

Mydb= mysql connecter connect (host="localhost", user=” root”)

Mycursor = mydb.cursor()

Def main()

Initiate()

while True

print(“1.. Add customer details")

print(“2. Update customer details”)

print (“3.Delete customer details”)

print(“4. Display all customer details")

print(“5.exit “)

try:

choose= int(input(“input:”))

except(valueerror,type error)

continue

if choose== 1

try:

name= input("Name”)

city=input(“city”)

category = int(input(“bill amount”))

except (value error, type error):

continue

data = (name,bill,city,category)

mycursor.execute (“INSERT INTO cus_name,bill,city,categorycustomer values (%s,%s,


%s,%s)”,data)

mydb.commit()
41

elif choose == 2

try:

c_id = int(input“id:”))

name=input(“new name:”)

city = input((“new category:”)

category= input(“new category:”)

bill= int(input(“new bill amount:”)

except (valueerror,typeerror):

Continue

Data=(name,bill,city,category,c_id)

Mycursor.execute(“UPDATE customer SET cus_name =%s,bill=%s,city=%sWHERE


cusid = %s”,data)

Mydb.commit()

Elif choose ==3

Try:

C_id = int(input(“customerid:”))

Except (valueerror,typeerror)

continue

data=((c_id))

my cursor.execute(“DELETE FROM Customer WHERE cusid=%s”,data)

mydb.commit()

elif choose == 4:

mycursor.execute(“SELECT * fROM customer”)

values = mycursor.fetchall()

for value in values:

print(value)

elif choose==5:

break

else:

continue
42

def initiate ():

try:

mycursor.execute(“use shop”)

except:

mycursor.execute(“CREATE DATABASE shop”)

mycursor.execute(“use shop”)

mycursor.execute(“CREATE TABLE customer(cusid INTEGER PRIMARY KEY


AUTO_INCREMENT,cus_name VARCHAR(20),bill INTEGER,city VARCHAR(20),category
VARCHAR(100))”)

if_name_==”_main_”:

main()

RESULTS:
43

You might also like