0% found this document useful (0 votes)
5 views17 pages

Python Practical File

The document outlines a series of Python programming practicals submitted by a student, Pratham Grover, to Mr. Mohit Dubey. It includes 24 programming tasks covering various topics such as string manipulation, file handling, data structures, and database connectivity. Each task is accompanied by a brief description and a sample code implementation.

Uploaded by

prathamgrover399
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)
5 views17 pages

Python Practical File

The document outlines a series of Python programming practicals submitted by a student, Pratham Grover, to Mr. Mohit Dubey. It includes 24 programming tasks covering various topics such as string manipulation, file handling, data structures, and database connectivity. Each task is accompanied by a brief description and a sample code implementation.

Uploaded by

prathamgrover399
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

PYTHON PROGRAMMING FILE

SUBMITTED TO Mr Mohit Dubey


SUBMITTED BY Pratham Grover , Class - XII-C

LIST OF PRACTICALS:

[Link] PROGRAM T. Sign


.
1 Write a program to show if the entered string is a palindrome or not.
Ans:def is_palindrome():
s = input("Enter a string: ").strip()
s_clean = [Link]().replace(" ", "") # Ignore spaces and case
if s_clean == s_clean[::-1]:
print(f"'{s}' is a palindrome.")
else:
print(f"'{s}' is not a palindrome.")
is_palindrome()
2 Write a program to show statistics of characters in the given line (to count the
number of alphabets, digits, uppercase, lowercase, spaces and other
characters).
Ans:def char_statistics():
line = input("Enter a line: ")
alphabets = digits = upper = lower = spaces = others = 0
for char in line:
if [Link]():
alphabets += 1
if [Link]():
upper += 1
else:
lower += 1
elif [Link]():
digits += 1
elif [Link]():
spaces += 1
else:
others += 1
print(f"Alphabets: {alphabets}")
print(f"Digits: {digits}")
print(f"Uppercase: {upper}")
print(f"Lowercase: {lower}")
print(f"Spaces: {spaces}")
print(f"Other characters: {others}")
char_statistics()
3 Write a program to display frequencies of all the elements of a list.
Ans: lst = eval(input("Enter a list: "))
freq = {}
for item in lst:
if item in freq:
freq[item] = freq[item] + 1
else:
freq[item] = 1
print("Element : Frequency")
for element in freq:
print(element, " :", freq[element])

4 Write a program to display those strings which are starting with ‘A’ from the
given list.
Ans: def starts_with_A():
lst = eval(input("Enter a list of strings (e.g., ['Apple', 'Bat', 'Ant']): "))
result = [s for s in lst if [Link]('A')]
print("Strings starting with 'A':", result)
starts_with_A()
5 Write a program to find and display the sum of all the values which are
ending with 3 from a list.
Ans: def sum_ending_with_3():
lst = eval(input("Enter a list of numbers (e.g., [13, 25, 33, 41]): "))
total = sum(x for x in lst if str(x).endswith('3'))
print("Sum of numbers ending with 3:", total)
sum_ending_with_3()
6 Write a program to delete the duplicate element from the list
Ans:def remove_duplicates():
lst = eval(input("Enter a list: "))
unique = list([Link](lst)) # Preserves order
# Or: unique = list(set(lst)) # Doesn't preserve order
print("List after removing duplicates:", unique)
remove_duplicates()
7 Write a program to swap the content with next value, if it is divisible by 7
Ans:def swap_if_divisible_by_7():
lst = eval(input("Enter a list of numbers: "))
i=0
while i < len(lst) - 1:
if lst[i] % 7 == 0:
lst[i], lst[i+1] = lst[i+1], lst[i]
i += 1 # Skip next element as it has been swapped
i += 1
print("Modified list:", lst)
swap_if_divisible_by_7()
8 Write a program to accept values from a user and create a tuple.
Ans:def create_tuple():
n = int(input("How many elements? "))
elements = []
for i in range(n):
val = input(f"Enter element {i+1}: ")
try:
val = int(val) if [Link]() else float(val) if '.' in val else val
except:
pass
[Link](val)
t = tuple(elements)
print("Created tuple:", t)
create_tuple()
9 Write a program to input the names of ‘n’ countries and their capital store in a
dictionary.
Ex d = {“India”:”New Delhi” ,……}
Ans:def country_capitals():
n = int(input("Enter number of countries: "))
d = {}
for i in range(n):
country = input("Enter country name: ")
capital = input("Enter capital: ")
d[country] = capital
print("Dictionary:", d)
country_capitals()
10 Write a program to show GCD of two positive numbers.
Ans:import math
def gcd_two_numbers():
a = int(input("Enter first positive number: "))
b = int(input("Enter second positive number: "))
print("GCD:", [Link](a, b))
gcd_two_numbers()
11 Write a function in python to read lines from text file [Link] and display
words which are less than four character
Ans:def short_words_poem():
try:
with open("[Link]", "r") as f:
for line in f:
words = [Link]().split()
short = [w for w in words if len(w) < 4]
if short:
print(short)
except FileNotFoundError:
print("[Link] not found!")
short_words_poem()
12 Write a program to show and count the number of words in a text file
‘[Link]’ which is starting with the words' The', ‘the’.
Ans:def count_the_words():
count = 0
try:
with open("[Link]", "r") as f:
for line in f:
words = [Link]()
for word in words:
if [Link]().startswith("the"):
count += 1
print(word)
print("Total words starting with 'The/the':", count)
except FileNotFoundError:
print("[Link] not found!")
count_the_words()
13 Write a program to read data from a text file [Link], and display each
word with a number of vowels and consonants.
Ans:def vowels_consonants():
try:
with open("[Link]", "r") as f:
for line in f:
words = [Link]()
for word in words:
word_clean = ''.join([Link]() for ch in word if [Link]())
vowels = sum(1 for ch in word_clean if ch in 'aeiou')
consonants = len(word_clean) - vowels
print(f"{word} -> Vowels: {vowels}, Consonants:
{consonants}")
except FileNotFoundError:
print("[Link] not found!")
vowels_consonants()

14 Write a program to read data from a text file [Link], and display words
which have maximum/minimum characters.
Ans:def max_min_length_words():
try:
words = []
with open("[Link]", "r") as f:
for line in f:
[Link]([Link]())
if not words:
print("File is empty.")
return
min_len = min(len(w) for w in words)
max_len = max(len(w) for w in words)
min_words = [w for w in words if len(w) == min_len]
max_words = [w for w in words if len(w) == max_len]
print("Words with minimum characters:", min_words)
print("Words with maximum characters:", max_words)
except FileNotFoundError:
print("[Link] not found!")
max_min_length_words()
15 Consider a binary file “[Link] '' containing details such as empno:
ename:salary(separator‘:’).Write a python function to display details of those
employees who are earning between 20000 and 40000.
Ans:import pickle
def display_salary_range():
try:
with open("[Link]", "rb") as f:
print("Employees with salary between 20000 and 40000:")
while True:
try:
record = [Link](f)
empno, ename, salary = [Link](':')
salary = float(salary)
if 20000 <= salary <= 40000:
print(f"EmpNo: {empno}, Name: {ename}, Salary: {salary}")
except EOFError:
break
except FileNotFoundError:
print("[Link] not found!")
display_salary_range()

16 Write a program to insert list data in a CSV File and print it.
Ans:import csv
def list_to_csv():
data = eval(input("Enter list of lists (e.g., [['Name','Age'],['Ram',20]]): "))
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](data)
print("Data written to [Link]")
# Print content
with open("[Link]", "r") as f:
print([Link]())
list_to_csv()
17 Following is the structure of each record in a data file named”
[Link]”.
{"prod_code":value, "prod_desc":value, "stock":value}
The values for prod_code and prod_desc are strings, and the value for stock is
an integer.
Write a program in PYTHON to update the file with a new value of stock.
The stock and the product_code, whose stock is to be updated, are to be input
during the execution of the function.
Ans:import pickle
def update_stock():
prod_code = input("Enter product code to update: ")
new_stock = int(input("Enter new stock value: "))
found = False
records = []
try:
with open("[Link]", "rb") as f:
while True:
try:
rec = [Link](f)
[Link](rec)
if rec["prod_code"] == prod_code:
rec["stock"] = new_stock
found = True
except EOFError:
break
if found:
with open("[Link]", "wb") as f:
for rec in records:
[Link](rec, f)
print("Stock updated successfully.")
else:
print("Product code not found.")
except FileNotFoundError:
print("[Link] not found!")
update_stock()
18 Assuming the tuple Vehicle as follows:
( vehicletype, no_of_wheels)
Where vehicletype is a string and no_of_wheels is an integer.
Write a program to read all the records present in an already existing binary
file [Link] and display them on the screen, also count the number of
records present in the file.
Ans:import pickle
def display_vehicles():
count = 0
try:
with open("[Link]", "rb") as f:
while True:
try:
vehicletype, wheels = [Link](f)
print(f"Vehicle Type: {vehicletype}, Wheels: {wheels}")
count += 1
except EOFError:
break
print("Total records:", count)
except FileNotFoundError:
print("[Link] not found!")
display_vehicles()
19 Write a MENU DRIVEN program to show push and pop operation using
stack.
Ans:def stack_menu():
stack = []
while True:
print("\n1. Push\n2. Pop\n3. Display\n4. Exit")
ch = input("Enter choice: ")
if ch == '1':
item = input("Enter item to push: ")
[Link](item)
print("Pushed:", item)
elif ch == '2':
if stack:
print("Popped:", [Link]())
else:
print("Stack empty!")
elif ch == '3':
print("Stack:", stack)
elif ch == '4':
break
stack_menu()
20 Write a Python program to create a dictionary from a string. . A
Note: Track the count of the letters from the string.
Sample string : 'computeerr'
Expected output: {c:1 ,o:1,m:1 , p:1, u,:1 ,t:1 , e:2 ,r:2}
Ans: def letter_count_dict():
s = input("Enter a string: ")
d = {}
for ch in s:
d[ch] = [Link](ch, 0) + 1
print(d)
letter_count_dict()

21 Write a Python program to combine two dictionary adding values for


common keys. .
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
Ans: from collections import Counter
def combine_dicts():
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
result = Counter(d1) + Counter(d2)
print(result)
combine_dicts()
22 Write a Program in Python to sort a tuple of tuples by 2nd item
tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
Expected output:
(('c', 11), ('a', 23), ('d', 29), ('b', 37))
Ans: def sort_tuple_by_second():
tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))
sorted_tuple = tuple(sorted(tuple1, key=lambda x: x[1]))
print(sorted_tuple)
sort_tuple_by_second()
23 Assume a MySQL database named Library with a table named Books that
has the following structure:
Books (BookID INT PRIMARY KEY, Title VARCHAR(100), Author
VARCHAR(50), Price DECIMAL(10, 2), Stock INT)
insert_book(book_id, title, author, price, stock):function should
connect to the database and insert a new record into the Books table
using the provided arguments.

display_low_stock():function should retrieve and display all book


records where the Stock quantity is strictly less than 5. The output
should be formatted neatly (e.g., using print statements or a simple
table format).

update_price(book_id, new_price):function should update the Price field


for a specified BookID.

delete_book():This function should prompt the user to enter a BookID via


the console.

Ans: import [Link]

def library_functions():

conn = [Link](

host="localhost", user="root", password="password",


database="Library"

cur = [Link]()

def insert_book(book_id, title, author, price, stock):

[Link]("INSERT INTO Books VALUES (%s, %s, %s, %s, %s)",

(book_id, title, author, price, stock))

[Link]()

print("Book inserted.")

def display_low_stock():

[Link]("SELECT * FROM Books WHERE Stock < 5")

rows = [Link]()

if rows:

print("Low Stock Books:")

for row in rows:

print(row)
else:

print("No low stock books.")

def update_price(book_id, new_price):

[Link]("UPDATE Books SET Price = %s WHERE BookID = %s",


(new_price, book_id))

[Link]()

print("Price updated.")

def delete_book():

book_id = int(input("Enter BookID to delete: "))

[Link]("DELETE FROM Books WHERE BookID = %s",


(book_id,))

[Link]()

print("Book deleted.")

insert_book(1, "Python", "Guido", 500.00, 10)

display_low_stock()

[Link]()
24 Write a python program with Mysql connectivity based on above table:
Hospital

Hospital_i Hospital_ Bad Count


d Name
1 Apollo 200
Hospital

2 Yashoda 400
Hospital
3 Max 1000
Hospital

4 Life 1500
Hospital
Doctor

Doctor_id Doctor_Name Hospital_id Joining_Date Speciality Salary Exp.


101 Dr. Anuj 1 2005-12-05 Oncologist 250000 Null

102 Dr. Amit 2 2012-11-22 Radiologis 260000 Null


t
103 Dr. Rajni 2 2013-11-12 Pediatric 270000 Null

104 Dr. Jyoti 4 2008-07-03 Oncologist 210000 Null

i Fetch Hospital and Doctor Information using hospital Id and doctor Id


Ans: import [Link]
from datetime import datetime
def hospital_doctor_queries():
conn = [Link](
host="localhost", user="root", password="password",
database="dbstation"
)
cur = [Link]()
def fetch_hospital_doctor(hosp_id, doc_id):
[Link]("""
SELECT h.Hospital_Name, d.Doctor_Name
FROM Hospital h JOIN Doctor d ON h.Hospital_id = d.Hospital_id
WHERE h.Hospital_id = %s AND d.Doctor_id = %s
""", (hosp_id, doc_id))
print([Link]())
ii Get the list Of doctors as per the given specialty and salary
Ans: def doctors_by_specialty_salary(specialty, min_salary):
[Link]("SELECT * FROM Doctor WHERE Speciality = %s AND
Salary >= %s",
(specialty, min_salary))
for row in [Link]():
print(row)
iii Get a list of doctors from a given hospital
Ans: def doctors_in_hospital(hosp_id):
[Link]("SELECT Doctor_Name FROM Doctor WHERE
Hospital_id = %s", (hosp_id,))
for row in [Link]():
print(row[0])
iv Update doctor experience in years
Ans: def update_experience():
[Link]("SELECT Doctor_id, Joining_Date FROM Doctor")
for doc_id, join_date in [Link]():
years = ([Link]().date() - join_date).days // 365
[Link]("UPDATE Doctor SET Exp = %s WHERE Doctor_id =
%s", (years, doc_id))
[Link]()
print("Experience updated.")
v add record in Doctor table .
Ans: def add_doctor():
doc_id = int(input("Doctor ID: "))
name = input("Name: ")
hosp_id = int(input("Hospital ID: "))
join_date = input("Joining Date (YYYY-MM-DD): ")
specialty = input("Speciality: ")
salary = float(input("Salary: "))
[Link]("INSERT INTO Doctor VALUES (%s, %s, %s, %s, %s, %s,
NULL)",
(doc_id, name, hosp_id, join_date, specialty, salary))
[Link]()
print("Doctor added.")
[Link]()

You might also like