Functions and File Handling
Q1: Write a recursive function to calculate the factorial of a number.
def recur_factorial(n):
if n == 1 or n == 0: # Include 0! = 1
return 1
else:
return n * recur_factorial(n - 1)
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers.")
else:
print("Factorial of", num, "is", recur_factorial(num))
Output:
Enter a number: 4
Factorial of 4 is 24
Q2: Write a function to display Fibonacci series using recursion.
def recur_fibo(n):
if n <= 1:
return n
else:
return recur_fibo(n - 1) + recur_fibo(n - 2)
nterms = int(input("How many terms are required? "))
print("Fibonacci sequence generated is:")
for i in range(nterms):
print(recur_fibo(i))
Output:
How many terms required? 3
Fibonacci sequence generated is:
0
1
1
Q3: User-defined function to count occurrences of a character in a string.
def countchar(s, ch):
count = 0
for i in s:
if i == ch:
count += 1
return count
str_input = input("Enter any string: ")
ch1 = input("Enter the character to count: ")
result = countchar(str_input, ch1)
if result == 0:
print(f"{ch1} does not exist in the string")
else:
print(f"{ch1} exists {result} times in the string")
Output:
Enter any string: deepak
Enter the character to count: e
e exists 2 times in the string
Q4: Calculate the arithmetic mean of list elements.
def list_avg(lst):
total = sum(lst)
return total / len(lst)
print("Input integers: ")
a = list(map(int, input().split()))
avg = list_avg(a)
print("Average is:", round(avg, 2))
Output:
Input integers:
456782
Average is: 5.33
Q5: Write a function to find the maximum of three numbers using recursion.
def max_of_two(x, y):
return x if x > y else y
def max_of_three(x, y, z):
return max_of_two(x, max_of_two(y, z))
print(max_of_three(8, -4, 10))
Output:
10
Q6: Write a program that accepts a string and calculates the number of uppercase and
lowercase letters.
def string_test(s):
d = {"upper_case": 0, "lower_case": 0}
for c in s:
if c.isupper():
d["upper_case"] += 1
elif c.islower():
d["lower_case"] += 1
print('Original string:', s)
print('Number of uppercase characters:', d["upper_case"])
print('Number of lowercase characters:', d["lower_case"])
string_test('Play learn and grow')
Output:
Original string: Play learn and grow
Number of uppercase characters: 1
Number of lowercase characters: 15
Q7: WAP to display details of employees earning between 20000 and 40000 from a binary
file "Employee.dat".
def Readfile():
with open("Employee.dat", "rb") as f:
line = f.readline()
while line:
data = line.split(':')
salary = float(data[2])
if 20000 <= salary <= 40000:
print(line)
line = f.readline()
Readfile()
Note: Ensure that 'Employee.dat' is structured correctly and opened in binary mode for proper
reading.
Q8: Write a function to count the occurrences of "my" in a text file "DATA.TXT".
def countmy():
with open("DATA.TXT", "r") as f: # open in text mode
content = f.read()
count = content.split().count("my")
print(f"'my' occurs {count} times.")
countmy()
Output:
'my' occurs 5 times.
Q9: Program using dictionary and text files to store Roman numerals and their
equivalents.
import pickle
# Store Roman numeral equivalents
roman_dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500:
'D', 900: 'CM', 1000: 'M'}
with open("roman.log", "wb") as f:
pickle.dump(roman_dict, f)
# Read Roman numeral equivalents
with open("roman.log", "rb") as f:
roman_data = pickle.load(f)
n=0
while n != -1:
print("Enter 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000")
print("Enter -1 to exit")
n = int(input("Enter a numeral: "))
if n != -1 and n in roman_data:
print(f'Equivalent Roman numeral is: {roman_data[n]}')
else:
print("Thank you")
Q10: Program to search the record of a particular student by name in a CSV file.
import csv
with open("student.csv", "r") as f:
csv_reader = csv.reader(f)
name = input("Enter the name to search: ")
for row in csv_reader:
if row[0] == name:
print(row)
Output:
Enter the name to search: jatin
['jatin', 'XII', '70']
Q11: Program to count the exact number of records present in a CSV file (excluding the
header).
import csv
with open("student.csv", 'r') as f:
csv_reader = csv.reader(f)
next(csv_reader) # Skip header
records = list(csv_reader)
print(f"No. of records are: {len(records)}")
Output:
No. of records are: 10
Q12: Program to read byte by byte from a file using seek() and tell().
with open("test1.txt", "r") as f:
print("Before reading:", f.tell())
content = f.read()
print("After reading:", f.tell())
f.seek(0)
print("From the beginning again:", f.tell())
print("First 4 bytes are:", f.read(4))
print(f.tell())
print("Next 3 bytes are:", f.read(3))
print(f.tell())
Q13: Program to update the name of a student by roll number in a binary file
'student.dat'.
import pickle
with open("student.dat", "rb+") as f:
student_records = pickle.load(f)
rollno = int(input("Enter the roll number to search: "))
for student in student_records:
if student[0] == rollno:
print("Current name is:", student[1])
student[1] = input("New name: ")
f.seek(0)
pickle.dump(student_records, f)
print("Name updated!!!")
break
Output:
Enter the roll number to search: 2
Current name is: Radhika
New name: Sonia
Name updated!!!
Q14: Program to read records from a binary file 'student.dat'.
import pickle
with open("student.dat", "rb") as f:
student_records = pickle.load(f)
print("Contents of student file are:")
for student in student_records:
roll_no, name, marks = student
print(roll_no, name, marks)
Output:
Contents of student file are:
2 Radhika 490
3 Shaurya 450
Q15: User-defined function to count the number of vowels in a string.
def count_vowels(s):
count = 0
vowels = "aeiouAEIOU"
for ch in s:
if ch in vowels:
count += 1
return count
str_input = input("Enter any string: ")
count = count_vowels(str_input)
print(f"Total number of vowels present in the string are: {count}")
Output:
Enter any string: function provides code reusability
Total number of vowels present in the string are: 13
Mysql
Create database student;
Use student;
CREATE TABLE student (
roll_no INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
dob DATE,
guid CHAR(36) NOT NULL
);
INSERT INTO student (roll_no, name, dob, guid) VALUES
(1, 'Ramesh', '2000-01-15', 'A01'),
(2, 'Raghav', '2001-05-23', 'B02'),
(3, 'Ankita', '2002-09-10', 'C03'),
(4, 'Deepka', '1999-12-20', 'D04'),
(5, 'Yenika', '2003-03-30', 'E05');
mysql> select* from student;
+---------+--------+------------+------+
| roll_no | name | dob | guid |
+---------+--------+------------+------+
| 1 | Ramesh | 2000-01-15 | A01 |
| 2 | Raghav | 2001-05-23 | B02 |
| 3 | Ankita | 2002-09-10 | C03 |
| 4 | Deepka | 1999-12-20 | D04 |
| 5 | Yenika | 2003-03-30 | E05 |
+---------+--------+------------+------+
5 rows in set (0.00 sec)
mysql> describe student;
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| roll_no | int | NO | PRI | NULL | |
| name | varchar(100) | NO | | NULL | |
| dob | date | YES | | NULL | |
| guid | char(36) | NO | | NULL | |
+---------+--------------+------+-----+---------+-------+
4 rows in set (0.02 sec)
# How to search record of a table
import mysql.connector
# Establish the connection
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
# Get student name from user input
student_name = input("Enter student name: ")
# Search for the record
query = "SELECT * FROM student WHERE name = %s"
cursor.execute(query, (student_name,))
#Fetch and print the result
result = cursor.fetchall()
if result:
for row in result:
print(row)
else:
print("No record found.")
# Close the connection
cursor.close()
connection.close()
import mysql.connector
Fetch all records of the table
# Establish the connection
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
query = "SELECT * FROM student"
cursor.execute(query)
result = cursor.fetchall()
for i in result:
print(i)
cursor.close()
connection.close()
Adding a column in table
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
#Add a column
query = "alter table student add marks int "
cursor.execute(query)
cursor.close()
connection.close()
Updating the value
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
#Add a column
query = "update student set marks = 90 where ( roll_no =3 and 4) "
cursor.execute(query)
cursor.close()
connection.close()
Q WAP to update student marks to 90 where name is Deepka
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
#Add a column
query = "update student set marks = 90 where name ='Deepka'"
cursor.execute(query)
cursor.close()
connection.close()
Q WAP to delete record where name is Ramesh
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
# Create a cursor object
cursor = connection.cursor()
#Add a column
query = "delete from student where name ='Ramesh'"
cursor.execute(query)
cursor.close()
connection.close()