0% found this document useful (0 votes)
40 views58 pages

PYTHON 12th (1)

This document certifies that Jai Kumar Sharma has completed a research project in computer science under the guidance of Rakesh Choudhary for the academic year 2024-2025. It includes an acknowledgment section expressing gratitude to teachers, parents, and friends, and provides an introduction to Python programming along with a list of practical programs and their implementations. The document serves as a practical file for the computer science examination conducted by GBSSS Gokalpuri Village Delhi.
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)
40 views58 pages

PYTHON 12th (1)

This document certifies that Jai Kumar Sharma has completed a research project in computer science under the guidance of Rakesh Choudhary for the academic year 2024-2025. It includes an acknowledgment section expressing gratitude to teachers, parents, and friends, and provides an introduction to Python programming along with a list of practical programs and their implementations. The document serves as a practical file for the computer science examination conducted by GBSSS Gokalpuri Village Delhi.
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/ 58

CERTIFICATE

This is to certify that Jai kumar sharma , a


student of class XII,B ROLL NO. - 22 has
successfully completed the research on the
computer science practical file under the
guidance of RAKESH CHOUDHARY
(Subject Teacher) during the year 2024 –
2025 in partial ful fillment of computer
science practical examination conducted by
GBSSS Gokalpuri Village Delhi.

Student name – Jai Kumar Sharma

__________
principal
____________
Examiner’s signature
ACKNOWLEDGEMENT

I would like to express my special thanks to my


computer teacher RAKESH CHOUDHARY (Computer
Teacher Name), who give me the golden opportunity
to do this wonderful practical file . I am also very
grateful to my other computer teachers and school
teachers for helping me with the necessary equipment
and valuable guidance.

Finally, I would like to thank my parents and close


friends, who were always with me from imagination to
the implementation of this project. Without their
cooperation, this project would not have been
completed. Only because of all of you, I was able to
make my project successful and make it a good
enjoyable experience.
INTRODUCTION
Python is an interpreted, high-level and general-
purpose programming language. Python's design
philosophy emphasizes code readability with its
notable use of significant whitespace. Its language
constructs and object-oriented approach aim to help
programmers write clear, logical code for small and
large-scale projects.

Python is dynamically typed and garbage-collected. It


supports multiple programming paradigms, including
structured (particularly, procedural), object-oriented,
and functional programming. Python is often described
as a "batteries included" language due to its
comprehensive standard library.

Since 2003, Python has consistently ranked in the top


ten most popular programming languages in the TIOBE
Programming Community Index where, as of February
2021, it is the third most popular language (behind
Java, and C).
S. Contents Date Pag Teacher
N of e ’s
o. Practic No.
Sign.
al

Python Programs

1 Write a program in Python to input a number from


the user and calculate if the given number is
prime or not.

2 Write a program in Python to input a string from


the user and find out if the given string is
palindrome or not.

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.

4 Write a program in Python, which input a list L of


numbers and a number to be searched. If the
number exists, it is replaced by 0 and if the
number does not exist, an appropriate message is
displayed.

5 Write a Python program, which takes a dictionary


Student as input, the dictionary Student
contains Name:(Phy,Chem,Math) as key:value
pairs, program should display the average marks
of all students present in the dictionary.

6 Write a Python program to read a text file


“POEM.TXT” and print the total number of
vowels and consonants separately present in
the text file.

7 Write a Python program to read a text file


“Input.txt” and print the words starting with ‘O’
(Lower/Upper both cases) in reverse order. The
rest of the content is displayed normally.

8 Write a Python program which reads the contents


of a text file "BIOPIC.TXT" and displays the
content of the file with every occurrence of the
word 'he' replaced by 'she'.

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

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

11 Create a binary file “Student.Dat” with the


name and roll
number. Search for a given roll number and
display the name, if not found display
appropriate message.

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.

13 Write a program using the following functions :


A binary file “Book.dat” has structure [BookNo,
Book_Name, Author, Price].

1. Write a user defined function CreateFile()


to input data for a record and add to
Book.dat .

2. Write a function CountRec(Author) in


Python which accepts the Author name as
parameter and count and return number of
books by the given
Author are stored in the binary file
“Book.dat”

14 Write a program to perform read and write


operation onto a “student.csv” file having fields
as roll number, name, stream and percentage.

15 Write a program to copy the data from


“Data.csv” to “Temp.csv”.

16 Write a program to create a library on your name


in python and import it in a 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.

18 A list contains following record of customer:


[Customer_name, Room_Type]
Write a complete program using the following
user defined function to perform given operations
on the stack named 'Hotel':
(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.

19 A school stores records of Class XII students using


a list that contains multiple lists as its elements.
The structure of each such element is
[Student_Name, Marks, MainSubject].
Crate a complete program using the user-defined
functions to perform the operations as mentioned
below:
(a) Push_student(): To push the Student_Name
and Marks of all those students, who have Science
as MainSubject, into a Stack StudentInfo
(b) Pop_student(): To delete all items (one at a
time) from the stack StudentInfo in LIFO order and
display them. Also display "Empty Stack" when
there are no items remaining in the stack.

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.

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):

# If num is divisible by any number between


# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output

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

# Iterate through the list


for num in L:
# Check if the number ends with the digit 3
if num % 10 == 3:
total += num # Add to the sum if it ends with 3

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

The sum of integers that end with 3 is: 235


Program 4: Write a program in Python, which input a list
L of numbers and a number to be searched. If the
number exists, it is replaced by 0 and if the number
does not exist, an appropriate message is displayed.

def replace_number_in_list(L, target):


# Check if the target number exists in the list
if target in L:
# Replace all occurrences of the target with 0
for i in range(len(L)):
if L[i] == target:
L[i] = 0
print("Updated List:", L)
else:
print(f"The number {target} does not exist in the list.")

L = list(map(int, input("Enter a list of numbers separated by spaces:


").split()))
target = int(input("Enter the number to search and replace with 0: "))

Enter a list of numbers separated by spaces: 10 20 30 40 50 20


Enter the number to search and replace with 0: 20
Output

Updated List: [10, 0, 30, 40, 50, 0]


Program 5: Write a Python program, which takes a
dictionary Student as input, the dictionary Student
contains Name:(Phy,Chem,Math) as key:value pairs,
program should display the average marks of all
students present in the dictionary.

# Input: A dictionary where keys are student names and values are tuples
with marks (Phy, Chem, Math)
student_dict = {}

# Take input for the dictionary


n = int(input("Enter the number of students: "))

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

Average marks of Charlie: 86.33.


Program 6: Write a Python program to read a text file
“POEM.TXT” and print the total number of vowels and
consonants separately present in the text file.

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

Total number of vowels: 19


Total number of consonants: 25
Program 7: Write a Python program to read a text file
“Input.txt” and print the words starting with ‘O’
(Lower/Upper both cases) in reverse order. The rest of
the content is displayed normally.

def process_file(filename):
try:
lines = file.readlines()
for line in lines:
words = line.split()
processed_words = []

for word in words:


if word.lower().startswith('o'):
processed_words.append(word[::-1])
else:
processed_words.append(word)
print(" ".join(processed_words))
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 = "Input.txt"
process_file(filename)

Once upon a time, there was an Owl.


The Owl observed the ocean from a tree.
Output
ecnO upon a time, there was an wlO.
The wlO devresbo the naeco from a tree.
Program 8: Write a Python program which reads the
contents of a text file "BIOPIC.TXT" and displays the
content of the file with every occurrence of the word 'he'
replaced by 'she'.

def replace_word_in_file(filename, old_word, new_word):


try:
# Open the file and read its content
with open(filename, 'r') as file:
text = file.read()

# Replace occurrences of the word 'he' with 'she'


# Using case-insensitive replacement
updated_text = text.replace(' he ', ' she ').replace(' He ', '
She ')

# Display the updated content


print("Updated Content:")
print(updated_text)

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

Number of lines with exactly 5 words: 3


Program 11: Create a binary file “Student.Dat” with the
name and roll
number. Search for a given roll number and
display the name, if not found display
appropriate message.

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}")

def search_student_by_roll_number(filename, roll_number):


try:
with open(filename, 'rb') as file:
students = pickle.load(file)
for student in students:
if student['roll_number'] == roll_number:
print(f"Name: {student['name']}")
return
print("Roll number not found.")
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
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)

input(during file creation )


Enter the number of students: 2
Enter roll number: 101
Enter name: Alice
Enter roll number: 102
Enter name: Bob

Input (During search)


Enter the roll number to search: 101
Output

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)

for student in students:


if student['roll_number'] == roll_number:
print(f"Existing details: Name: {student['name']}, Marks:
{student['marks']}")
student['name'] = input("Enter new name: ")
student['marks'] = float(input("Enter new marks: "))
updated = True
break
if updated:
with open(filename, 'wb') as file:
pickle.dump(students, file)
print("Details updated successfully.")
else:
print("Roll number not found.")

except FileNotFoundError:
print(f"Error: The file '{filename}'does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

Input (during file creation):


Enter the number of students: 2
Enter roll number: 101
Enter name: Alice
Enter marks: 85.5
Enter roll number: 102
Enter name: Bob
Enter marks: 90.0

Input (during update):


Enter the roll number to update: 101
Existing details: Name: Alice, Marks: 85.5
Enter new name: Alicia
Enter new marks: 88.0
Output
Details updated
Program 13: Write a program using the following
functions :
A binary file “Book.dat” has structure [BookNo,
Book_Name, Author, Price].

1. Write a user defined function CreateFile() to input


data for a record and add to Book.dat .

2. Write a function CountRec(Author) in Python which


accepts the Author name as parameter and count
and return number of books by the given
Author are stored in the binary file “Book.dat”

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")

Assume Data.csv Contains:


Roll Number,Name,Stream,Percentage
101,Alice,Science,90.5
102,Bob,Commerce,85.2
103,Charlie,Arts,78.0
Output

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

def add(a, b):


"""Function to add two numbers."""
return a + b

def subtract(a, b):


"""Function to subtract two numbers."""
return a - b

def multiply(a, b):


"""Function to multiply two numbers."""
return a * b

def divide(a, b):


"""Function to divide two numbers."""
if b == 0:
return "Division by zero is not allowed."
return a / b

Import the Library in Another Program


import mylibrary
if __name__ == "__main__":
print(mylibrary.greet("Alice"))
a, b = 10, 5
print(f"{a} + {b} = {mylibrary.add(a, b)}")
print(f"{a} - {b} = {mylibrary.subtract(a, b)}")
print(f"{a} * {b} = {mylibrary.multiply(a, b)}")
print(f"{a} / {b} = {mylibrary.divide(a, b)}")

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

# Function to generate random even numbers between a given range


def generate_random_even_numbers(low, high, count=5):
if low > high:
low, high = high, low
if low % 2 != 0:
low += 1
if high % 2 != 0:
high -= 1
even_numbers = list(range(low, high + 1, 2))
if len(even_numbers) < count:
return "Not enough even numbers in the given range."
return random.sample(even_numbers, count)
low = int(input("Enter the lowest number: "))
high = int(input("Enter the highest number: "))
even_numbers = generate_random_even_numbers(low, high)
if isinstance(even_numbers, list):
print(f"Random even numbers: {even_numbers}")
print(f"Sum of these numbers: {sum(even_numbers)}")
else:
print(even_numbers)

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

John Doe has been added to the stack.


Alice Johnson has been added to the stack.
Charlie Green has been added to the stack.
Customer Charlie Green has been removed from the stack.
Customer Alice Johnson has been removed from the stack.
Customer John Doe has been removed from the stack.
Underflow: No customers in the stack
Program 19: A school stores records of Class XII students using a
list that contains multiple lists as its elements. The structure of
each such element is [Student_Name, Marks, MainSubject]. (a)
Push_student(): To push the Student_Name and Marks of all those
students, who have Science as MainSubject, into a Stack
StudentInfo(b) Pop_student(): To delete all items (one at a time)
from the stack StudentInfo in LIFO order and display them. Also
display "Empty Stack" when there are no items remaining in the
stack.
class StudentStack:
def __init__(self):
self.stack = [] # Initialize an empty stack
def Push_student(self, students):
for student in students:
name, marks, main_subject = student
if main_subject.lower() == 'science':
self.stack.append([name, marks])
print(f"{name} with marks {marks} has been added to the
stack.")
def Pop_student(self):
if len(self.stack) == 0:
print("Empty Stack: No students to pop.")
else:
popped_student = self.stack.pop() # Pop the top student record
from the stack
name, marks = popped_student
print(f"Student {name} with marks {marks} has been removed
from the stack.")
students = [
["John Doe", 85, "Science"],
["Jane Smith", 90, "Commerce"],
["Alice Johnson", 75, "Science"],
["Bob Brown", 60, "Arts"],
["Charlie Green", 95, "Science"]]
student_stack = StudentStack()student_stack.Push_student(students)
student_stack.Pop_student() # Pops Charlie Green
student_stack.Pop_student() # Pops Alice Johnson

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')

You might also like