Programs 12 A
Programs 12 A
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.
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.
RISHABH KUMAR
XII A (SCIENCE)
2
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
2
3 QUESTION 3
QUESTION 4
QUESTION 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)
2
output:
RESTART: C:/Users/rishabh/AppData/Local/Programs/Python/Python311/python
1.py
[3, 5, 6, 9, 10, 12]
2
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/
2
Python/Python311/ 1.py
[3, 5, 6, 9, 10, 12]
2
OUTPUT:
RESTART: C:/Users//AppData/Local/Programs/Python/Python311/ Sum of
integers ending with digit 3 = 159
2
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,
2
# 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
2
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
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
Output :
RESTART:C:
\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishabh
python4.py
2
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}")
2
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:
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:
2
OUTPUT:
RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py
Enter the number of terms: 7
2
Fibonacci Sequence:
0112358
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
2
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.")
2
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
2
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
2
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): ")
2
analyze_file(filename)
OUTPUT:
RESTART: C:\Users\Gunjan\AppData\Local\Programs\Python\Python311\rishABH
PYTHON 2.py
Vowels: 1134
Consonants: 2356
Uppercase characters: 3789
Lowercase characters: 3689
2
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:
2
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
2
def menu():
print("\nStack Operations Menu:")
print("1. Push")
2
print("2. Pop")
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.")
2
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
2
2
5. Exit
Enter your choice (1-5): 1
Enter the element to push: 10
10 pushed to stack.
PART – 2
DATA STRUCTURE AND SQL QUERIES.
QUESTION 1: Consider the following MOVIE table write the SQL queries based on it,
ANSWERS:
ANS (A):
2
ANS(B):
ANS(C):
ANS(D)
ANS(E)
ANS(F)
2
2
QUESTION 2
PID PNAME AGE DEPARTMEN DATE OF CHAR GENDER
T ADM GES
ANS(B)
ANS(C)
ANS(D)
2
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 .
M1 2021/12/2 1 2 107 93
0
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
2
M6 2021/12/2 2 3 97 68
5
ANWERS:
2
2
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:
2
QUESTION 5:
Q - Consider the following table (table name: stock) and write the queries:
(B)
2
(C)
(D)
(E)
2
2
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)
2
2
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."))
2
RESULT:
2
2
QUESTION 3:
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")
2
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”))
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
2
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
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_”:
2
main()
RESULTS:
2
2