PYTHON 12th (1)
PYTHON 12th (1)
__________
principal
____________
Examiner’s signature
ACKNOWLEDGEMENT
Python Programs
MySQL Queries
21
Program 1: Write a program in Python to input a number from the
user and calculate if the given number is prime or not.
python
num = 11
# Negative numbers, 0 and 1 are not primes
if num > 1:
# Iterate from 2 to n // 2
for i in range(2, (num//2)+1):
11 is a prime number
Program 2: Write a program in Python to input a string
from the user and find out if the given string is
palindrome or not.
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
Output
Yes
Program 3: Write a program in Python, which inputs a
list L of integers and displays the sum of all such
integers from the list L which end with the digit 3.
def sum_integers_ending_with_3(L):
# Initialize the sum to 0
total = 0
return total
L = list(map(int, input("Enter a list of integers separated by spaces:
").split()))
result = sum_integers_ending_with_3(L)
print("The sum of integers that end with 3 is:", result
Enter a list of integers separated by spaces: 13 23 33 44 53 63 10 73
Output
# Input: A dictionary where keys are student names and values are tuples
with marks (Phy, Chem, Math)
student_dict = {}
for _ in range(n):
name = input("Enter student name: ")
marks = tuple(map(int, input(f"Enter marks for {name} (Physics,
Chemistry, Math): ").split()))
student_dict[name] = marks
input
Enter the number of students: 3
Enter student name: Alice
Enter marks for Alice (Physics, Chemistry, Math): 85 90 80
Enter student name: Bob
Enter marks for Bob (Physics, Chemistry, Math): 78 83 92
Enter student name: Charlie
Enter marks for Charlie (Physics, Chemistry, Math): 88 76 95
Output
Average marks of Alice: 85.00
Average marks of Bob: 84.33
def count_vowels_and_consonants(filename):
try:
text = file.read()
vowels = "aeiouAEIOU" Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowel_count = 0
consonant_count = 0
for char in text:
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
print(f"Total number of vowels: {vowel_count}") print(f"Total
number of consonants: {consonant_count}")
except FileNotFoundError:
print(f"Error: The file {filename}'doesnotexist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
filename = "POEM.TXT"
count_vowels_and_consonants(filename)
Output
def process_file(filename):
try:
lines = file.readlines()
for line in lines:
words = line.split()
processed_words = []
# Example usage
filename = "Input.txt"
process_file(filename)
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
input
He was a visionary, and he always inspired everyone.
He believed in his dreams, and he worked hard to achieve
them.
Output
Updated Content:
She was a visionary, and she always inspired everyone.
She believed in her dreams, and she worked hard to achieve them.
Program 9: Write a Python program to count and display
the number of lines starting with ‘A’ (Lower/Upper both
cases) present in the text file “Lines.txt”.
def count_lines_starting_with_a(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
count = 0
for line in lines:
if line.strip().lower().startswith('a'):
count += 1
print(f"Number of lines starting with 'A' or 'a': {count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
filename = "Lines.txt"
count_lines_starting_with_a(filename)
input
Content of Lines.txt:
Apple trees are beautiful.
Bananas are tasty.
Always strive for excellence.
Ants are hardworking creatures.
Birds sing melodiously.
Output
Number of lines starting with 'A' or 'a': 3
Program 10: Write a Python program to count and
display the number of lines that have exactly 5 words in
it present in the text file “Story.txt”.
def count_lines_with_five_words(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
count = 0
for line in lines:
words = line.split() # Split the line into words
if len(words) == 5: # Check if the line has exactly 5 words
count += 1
print(f"Number of lines with exactly 5 words: {count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
filename = "Story.txt"
count_lines_with_five_words(filename)
input
The sun rises in the east.
It was a beautiful morning.
The cat chased the mouse.
She read the entire book quickly.
He smiled at her.
Output
import pickle
def create_student_file(filename):
try:
with open(filename, 'wb') as file:
students = []
n = int(input("Enter the number of students: "))
for _ in range(n):
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
students.append({'roll_number': roll_number, 'name':
name})
pickle.dump(students, file)
print(f"{filename} created successfully.")
except Exception as e:
print(f"An error occurred: {e}")
filename = "Student.Dat"
create_student_file(filename)
roll_to_search = input("Enter the roll number to search: ")
search_student_by_roll_number(filename, roll_to_search)
Name: Alice
Program 12: Create a binary file “Stud.dat” with roll
number, name and marks. Input a roll number and
update details. Create a binary file with roll number,
name and marks. Input a roll number and update
details.
import pickle
def create_student_file(filename):
try:
with open(filename, 'wb') as file:
students = []
n = int(input("Enter the number of students: "))
for _ in range(n):
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
marks = float(input("Enter marks: "))
students.append({'roll_number': roll_number, 'name': name,
'marks': marks})
pickle.dump(students, file)
print(f"{filename} created successfully.")
except Exception as e:
print(f"An error occurred: {e}")
def update_student_details(filename, roll_number):
try:
updated = False
with open(filename, 'rb') as file:
students = pickle.load(file)
except FileNotFoundError:
print(f"Error: The file '{filename}'does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
import pickle
def CreateFile():
try:
with open("Book.dat", "ab") as file:
BookNo = input("Enter Book Number: ")
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = {"BookNo": BookNo, "Book_Name": Book_Name,
"Author": Author, "Price": Price}
pickle.dump(record, file)
print("Record added successfully!")
except Exception as e:
print(f"An error occurred while adding the record: {e}")
def CountRec(author_name):
count = 0
try:
with open("Book.dat", "rb") as file:
while True:
try:
record = pickle.load(file)
if record["Author"].lower() == author_name.lower():
count += 1
except EOFError:
break
except FileNotFoundError:
print("File not found! Please create the file first.")
except Exception as e:
print(f"An error occurred while counting records: {e}")
return count
if __name__ == "__main__":
while True:
print("\nMenu")
print("1. Add Book Record")
print("2. Count Books by Author")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
CreateFile()
elif choice == "2":
author_name = input("Enter the Author's Name to count their
books: ")
count = CountRec(author_name)
print(f"Number of books by {author_name}: {count}")
elif choice == "3":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
1. Add Book Record
2. Count Books by Author
3. Exit
Output
Enter your choice: 1
Enter Book Number: B101
Enter Book Name: Learn Python
Enter Author Name: Alice
Enter Price: 350
Program 14: Write a program to perform read and write
operation onto a “student.csv” file having fields
as roll number, name, stream and percentage.
import csv
try:
with open("student.csv", "a", newline="") as file:
writer = csv.writer(file)
roll_number = input("Enter Roll Number: ")
name = input("Enter Name: ")
stream = input("Enter Stream: ")
percentage = float(input("Enter Percentage: "))
writer.writerow([roll_number, name, stream, percentage])
print("Record added successfully!")
except Exception as e:
print(f"Error while writing to the file: {e}")
def read_from_csv():
try:
with open("student.csv", "r") as file:
reader = csv.reader(file)
print(f"\n{'Roll Number':<15}{'Name':<20}{'Stream':<15}
{'Percentage':<10}")
print("-" * 60)
for row in reader:
print(f"{row[0]:<15}{row[1]:<20}{row[2]:<15}{row[3]:<10}")
except FileNotFoundError:
print("File not found! Please add records first.")
except Exception as e:
print(f"Error while reading the file: {e}")
# Main Program
if __name__ == "__main__":
while True:
print("\nMenu")
print("1. Add Student Record")
print("2. Display All Records")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
write_to_csv()
elif choice == "2":
read_from_csv()
elif choice == "3":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")Record added successfully!
Menu
1. Add Student Record
2. Display All Records
3. Exit
Output
Enter your choice: 1
Enter Roll Number: 101
Enter Name: Alice Enter
Stream: Science
Enter Percentage: 90.5
Record added successfully!
Program 15: Write a program to copy the data from
“Data.csv” to “Temp.csv”.
import csv
def copy_csv(source_file, destination_file):
try:
with open(source_file, "r") as source:
reader = csv.reader(source)
# Open the destination file in write mode
with open(destination_file, "w", newline="") as destination:
writer = csv.writer(destination)
# Copy each row from source to destination
for row in reader:
writer.writerow(row)
print(f"Data successfully copied from {source_file} to
{destination_file}.")
except FileNotFoundError:
print(f"Source file '{source_file}' not found!")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
copy_csv("Data.csv", "Temp.csv")
Roll Number,Name,Stream,Percentage
101,Alice,Science,90.5
102,Bob,Commerce,85.2
103,Charlie,Arts,78.0
Program 16: Write a program to create a library on your
name in python and import it in a program.
def greet(name):
"""Function to greet a user."""
return f"Hello, {name}! Welcome to my library."
Output
Hello, Alice! Welcome to my library.
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
Program 17: Write a program which adds any random
five even numbers in a list that falls between the
highest and the lowest number. Both highest and lowest
numbers are accepted from the user.
import random
Input:
Enter the lowest number: 10
Enter the highest number: 30
Output:
Random even numbers: [10, 12, 18, 22,
28]
Sum of these numbers: 90
Program 18: A list contains following record of
customer:[Customer_name, Room_Type]
(a) Push_Cust(): To push customers' names of those who
are staying in 'Delux' Room Type.
(b) Pop_Cust(): To pop the names of customers from the
stack and display them. Also display "Underflow" when
there are no customers in the stack.
class HotelStack:
def __init__(self):
self.stack = [] # Initialize an empty stack
def Push_Cust(self, customers):
for customer in customers:
name, room_type = customer
if room_type.lower() == 'delux':
self.stack.append(name)
print(f"{name} has been added to the stack.")
def Pop_Cust(self):
if len(self.stack) == 0:
print("Underflow: No customers in the stack.")
else:
popped_customer = self.stack.pop() # Pop a customer from the
stack
print(f"Customer {popped_customer} has been removed from the
stack.")
customers = [
["John Doe", "Delux"],
["Jane Smith", "Standard"],
["Alice Johnson", "Delux"],
["Bob Brown", "Suite"],
["Charlie Green", "Delux"]]
hotel_stack = HotelStack()
hotel_stack.Push_Cust(customers)
hotel_stack.Pop_Cust()
hotel_stack.Pop_Cust()
Output
Output
John Doe with marks 85 has been added to the stack.
Alice Johnson with marks 75 has been added to the stack.
Charlie Green with marks 95 has been added to the stack.
Student Charlie Green with marks 95 has been removed from the stack.
Student Alice Johnson with marks 75 has been removed from the stack.
Student John Doe with marks 85 has been removed from the stack.
Empty Stack: No students to pop.
Program 20: Write a program to connect Python with
MySQL using database connectivity and
perform the following operations on data in
Database: A) Create, B) Insert, C) Fetch, D) Update and
E) Delete the data.
import mysql.connector
def connect_to_mysql():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="your_password"
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def create_database():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS school_db")
print("Database 'school_db' created or already exists.")
connection.close()
def create_table():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("USE school_db")
cursor.execute("""
CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT
PRIMARY KEY,
name VARCHAR(255),age INT,
grade VARCHAR(50) )""")
print("Table 'students' created or already exists.")
connection.close()
def insert_data():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("USE school_db")
query = "INSERT INTO students (name, age, grade) VALUES (%s, %s,
%s)"
values = [("John Doe", 16, "10th"), ("Jane Smith", 17, "11th"), ("Alice
Brown", 16, "10th")]
cursor.executemany(query, values)
connection.commit() # Commit the changes to the database
print(f"{cursor.rowcount} rows inserted.")
connection.close()
def fetch_data():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("USE school_db")
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("Data fetched from 'students' table:")
for row in rows:
print(row)
connection.close()
def update_data():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("USE school_db")
query = "UPDATE students SET grade = %s WHERE name = %s"
values = ("12th", "John Doe")
cursor.execute(query, values)
connection.commit()
print(f"{cursor.rowcount} row(s) updated.")
connection.close()
def delete_data():
connection = connect_to_mysql()
if connection:
cursor = connection.cursor()
cursor.execute("USE school_db")
query = "DELETE FROM students WHERE name = %s"
values = ("Alice Brown",)
cursor.execute(query, values)
connection.commit()
print(f"{cursor.rowcount} row(s) deleted.")
connection.close()
def main():
create_database()
create_table()
insert_data()
fetch_data()
update_data()
fetch_data()
delete_data()
fetch_data()
if __name__ == "__main__":
main()
Output
Database 'school_db' created or already exists.
Table 'students' created or already exists.
3 rows inserted.
Data fetched from 'students' table:
(1, 'John Doe', 16, '10th')
(2, 'Jane Smith', 17, '11th')
(3, 'Alice Brown', 16, '10th')
1 row(s) updated.
Data fetched from 'students' table:
(1, 'John Doe', 16, '12th')
(2, 'Jane Smith', 17, '11th')
(3, 'Alice Brown', 16, '10th')
1 row(s) deleted.
Data fetched from 'students' table:
(1, 'John Doe', 16, '12th')
(2, 'Jane Smith', 17, '11th')