Computer Science Journal
Computer Science Journal
FUNCTIONS
1) Aim: Write a Python code to accept an integer number. Pass it to a function that returns
the number of factors. Finally, display whether the number is a prime number or not.
[Hint: A number of said to be a prime number if it has only two factors.]
Source code: -
# def count_factors(n):
"""Return the number of factors of n"""
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
return count
if factors == 2:
print(f"{num} is a Prime Number ✅")
else:
print(f"{num} is NOT a Prime Number ❌")
1
2) Aim: Write a Python code in Python to accept two numbers from the
user and find the HCF and LCM. Use a function to return the HCF of the
numbers. Calculate the LCM in the main program.
[Hint: LCM = Product of the numbers /HCF]
Source code: -
def find_hcf(a, b):
"""Function to return HCF (GCD) of two numbers"""
while b != 0:
a, b = b, a % b
return a
Output of code: -
2
3) Aim: Write a code in Python to find the sum of the series using function:
s = (1 * 2) + (2 * 3) +.........................+ (19 * 20)
Source code: -
def series_sum(n):
""" Function to calculate sum of series (i * (i+1))"""
total = 0
for i in range(1, n + 1):
total += i * (i + 1)
return total
# Main Program
result = series_sum(19)
print("Sum of the series =", result)
print("Sum of the series =", result)
Output of code: -
3
4) Aim: Write a Python code to generate the Fibonacci series up to n. Pass the value of 'n' to
a function and display all the numbers of the series in the function as a list of elements.
Sample Input: Enter the value of n: 100
Sample Output: [0, 1, 1, 2, 3, 5, 8,891
Source code: -
def fibonacci_series(limit):
"""Function to generate Fibonacci series up to 'limit'"""
series = [0, 1]
while True:
next_num = series[-1] + series[-2]
if next_num > limit:
break
series.append(next_num)
print("Fibonacci Series up to", limit, "=", series)
# Main Program
n = int(input("Enter the value of n: "))
fibonacci_series(n)
Output of code: -
Enter the value of n: 100
Fibonacci Series up to 100 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
4
5) Aim: Write a Python code to accept a word and pass it to a function. The
function checks whether it is a palindrome word or not and returns 1 if
yes, otherwise 0 (zero).
Sample Input: MALAYALAM
Sample Output: Palindrome Word
Source code: -
def is palindrome(word):
""" Function to check if a word is a palindrome"""
word = word.upper() # convert to uppercase for uniformity
if word == word[::-1]:
return 1
else:
return 0
# Main Program
word = input("Enter a word: ")
result = is palindrome(word)
if result == 1:
print("Palindrome Word")
else:
print("Not a Palindrome Word")
Output of code: -
5
6) Aim: Write a Python code to accept a word in lowercase and pass it to a function. Arrange
all the letters of the word in alphabetical order and display the result.
Sample Input: computer
Sample Output: cemoprtu
Source code: -
def arrange_alphabetical(word):
"""Function to arrange letters of a word in alphabetical order"""
sorted_word = ''.join(sorted(word))
return sorted_word
# Main Program
word = input("Enter a word in lowercase: ")
result = arrange_alphabetical(word)
print("Word in alphabetical order:", result)
Output of code: -
6
7) Aim: Write a Python code to accept a word/string in a mixed case and pass it to a
function. The function should count the number of vowels present in the given string and
return the number of vowels to the main program.
Sample Input: Computer Science
Sample Output: No. of vowels = 6
Source code: -
def count_vowels(text):
"""Function to count vowels in a given string"""
vowels = "aeiouAEIOU"
count = 0
for ch in text:
if ch in vowels:
count += 1
return count
# Main Program
string = input("Enter a word/string: ")
vowel_count = count_vowels(string)
print("No. of vowels =", vowel_count)
Output of code: -
7
8) Aim: - Write a Python code to assign some names in a list. Pass the list to a function and
arrange the names in an alphabetical order by using 'Bubble Sort' technique. Display the
arranged names.
Source code: -
def bubble_sort(names):
"""Function to arrange names in alphabetical order using Bubble Sort"""
n = len(names)
for i in range(n - 1):
for j in range(n - i - 1):
if names[j] > names[j + 1]:
# Swap
names[j], names[j + 1] = names[j + 1], names[j]
return names
# Main Program
names_list = ["Sanjay", "Amit", "Kiran", "Zoya", "Priya", "Deepak"]
sorted_names = bubble_sort(names_list)
Output of code: -
8
9) Aim: Write a Python code to accept a set of integers in a list. Now, enter a number to
check whether it is available in the list or not by using the binary search technique. If found,
then display "Number is Present", otherwise display "Number is not present". Make use of a
function that accepts the list as a parameter and returns True or False accordingly.
Source code: -
def binary_search(arr, target):
"""Function to perform binary search"""
low = 0
high = len(arr) - 1
# Main Program
# Step 1: Accept list of integers
numbers = list(map(int, input("Enter integers separated by space: ").split()))
Output of code: -
9
10) Aim: - Write a Python code to accept some words in lowercase in a tuple. Pass the tuple
to a function and display only those words which start with a vowel. The function has no
return value to the main program.
Source code: -
def display_vowel_words(words):
"""Function to display words starting with a vowel"""
vowels = ('a', 'e', 'i', 'o', 'u')
print("Words starting with a vowel:")
for word in words:
if word.startswith(vowels):
print(word)
# Main Program
# Accept words in lowercase and store in tuple
words_tuple = tuple(input("Enter words in lowercase separated by space: ").split())
Output of code: -
Enter words in lowercase separated by space: apple orange banana mango umbrella cat
Words starting with a vowel:
apple
orange
umbrella
10
Functions & recursion
RECURSION
1) Aim: Write a Python code to input a base number and an index. The program calculates
and displays the magnitude of the index, raised to a base by using a recursive function.
Sample Input: Enter a base number: 5
Enter index: 4
Sample Output: 625 (i.e., 5^4)
Source code: -
def power(base, index):
"""Recursive function to calculate base^index"""
if index == 0:
return 1
else:
return base * power(base, index - 1)
# Main Program
base = int(input("Enter a base number: "))
index = int(input("Enter index: "))
11
2) Aim: Write a Python code to input a number 'm'. Find and display the sum of all the odd
numbers from 1 to 'm' by using a recursive function.
Source code: -
def sum_of_odds(n):
"""Recursive function to return sum of odd numbers from 1 to n"""
if n == 0:
return 0
elif n % 2 == 1:
return n + sum_of_odds(n - 1)
else:
return sum_of_odds(n - 1)
# Main Program
m = int(input("Enter a number: "))
result = sum_of_odds(m)
print("Sum of odd numbers from 1 to", m, "=", result)
12
3) Aim: Write a Python code to input a number and display the sum of its digits by using a
recursive function.
Sample Input: Enter a number: 348
Sample Output: Sum of the digits: 15
Source code: -
def sum_of_digits(n):
"""Recursive function to return the sum of the digits of n"""
if n == 0:
return 0
else:
return (n % 10) + sum_of_digits(n // 10)
# Main Program
num = int(input("Enter a number: "))
result = sum_of_digits(num)
13
4) Aim: Write a Python code to input two numbers. Use a recursive function which returns
HCF of the numbers.
Sample Input: 45, 60
Sample Output: HCF of 25 and 45 = 15
Source code: -
def sum_of_digits(n):
"""Recursive function to return sum of digits of n"""
if n == 0:
return 0
else:
return (n % 10) + sum_of_digits(n // 10)
# Main Program
num = int(input("Enter a number: "))
result = sum_of_digits(num)
14
5) Aim: Write a Python code to input a number and display the new number after reversing
its digits. Use a recursive function that returns a number after reversing the digits of the
number passed as an argument.
Sample Input:
Enter a number: 247
Sample Output:
Reversed Number: 742
Source code: -
def reverse_number(n, rev=0):
"""Recursive function to reverse digits of a number"""
if n == 0:
return rev
else:
return reverse_number(n // 10, rev * 10 + n % 10)
# Main Program
num = int(input("Enter a number: "))
result = reverse_number(num)
print("Reversed Number:", result)
15
6) Aim: Write a Python code to input a string and reverse the original string by using a
recursive function. Display the new string.
Sample Input:
Enter a word: COMPUTER
Sample Output:
The reverse word: RETUPMOC
Source code: -
def reverse_string(s):
"""Recursive function to reverse a string"""
if len(s) == 0:
return ""
else:
return reverse_string(s[1:]) + s[0]
# Main Program
word = input("Enter a word: ")
result = reverse_string(word)
print("The reverse word:", result)
16
7) Aim: Write a code in Python to input a string. Count and display the number of vowels
present in the given string by using a recursive function.
Sample Input: Computer Science
Sample Output: Number of vowels = 6
Source code: -
def count_vowels(s):
"""Recursive function to count vowels in a string"""
vowels = "aeiouAEIOU"
if s == "":
return 0
if s[0] in vowels:
return 1 + count_vowels(s[1:])
else:
return count_vowels(s[1:])
# Main Program
text = input("Enter a string: ")
result = count_vowels(text)
print("Number of vowels =", result)
17
8) Aim: Write a Python code to input a number and check whether it is an Armstrong
number or not by using a recursive technique.
A number is said to be 'Armstrong' if the sum of its digits raised to the power of the length of
the number is equal to the original number.
For example:
153-13+33+53=1+27+125=153
1634-14+64+34+44=1+1296+81+256=1634
Source code: -
def Sum_Pow(n, power):
"""Recursive function to calculate sum of digits^power"""
if n == 0:
return 0
else:
return (n % 10) ** power + Sum_Pow(n // 10, power)
def IsArmstrong(num):
power = len(str(num)) # length of number
total = Sum_Pow(num, power)
if total == num:
print(num, "is an Armstrong number")
else:
print(num, "is NOT an Armstrong number")
# Main program
num = int(input("Enter a number: "))
IsArmstrong(num)
18
9) Aim: Write a recursive function def Max_Ele(Lst) to input some elements in a list Lst.
The function returns to display the largest element present in the given list.
Sample Input:
[42, 51, 23, 99, 44, 31, 76, 81]
Sample Output: Largest element: 99
Source code: -
def Max_Ele(Lst):
# Base case: if list has only one element, return it
if len(Lst) == 1:
return Lst[0]
else:
# Recursive case: compare first element with max of the rest
max_rest = Max_Ele(Lst[1:])
return Lst[0] if Lst[0] > max_rest else max_rest
# Main program
Lst = [42, 51, 23, 99, 44, 31, 76, 81]
print("Largest element:", Max_Ele(Lst))
19
10) Aim: Write a program to input a set of numbers in a list. Enter a number and search
whether the number is present in the list or not by using 'Binary Search' technique. If the
number is present then display a message "Number is present", otherwise display "Number is
not present". Use a recursive function which returns 1 if the number to be searched in the list
is found, otherwise it returns 0 (zero).
Source code: -
def binary_search(lst, low, high, key):
if low > high:
return 0 # Not found
if lst[mid] == key:
return 1
elif key < lst[mid]:
return binary_search(lst, low, mid - 1, key)
else:
return binary_search(lst, mid + 1, high, key)
# Main program
lst = []
nums = input("Enter numbers separated by spaces: ").split()
20
DATA STRUCTURES
(STACKS & QUEUES)
1)Aim: Write a user-defined Python code to accept any five integer numbers in a queue.
Thereafter, insert a number (say, num). Find and display the frequency of 'num' by retrieving
each element from the queue.
Source code: -
def frequency_in_queue():
queue = []
# Input 5 integers
print("Enter 5 integers:")
for i in range(5):
n = int(input("Enter number " + str(i+1) + ": "))
queue.append(n)
21
2) Aim: You have stored a list containing ten integers. Thereafter, create a program with
separate user-defined functions to perform the following operations based on this list.
Traverse the content of the list and push all the perfect square numbers into a stack.
Pop and display the content of the stack.
For example, 16 is a perfect square number.
√16 = 4 and 4* 4 = 16
A list is defined as: MyList = [16, 44, 55, 64, 80, 81, 49, 66, 99, 75]
Source code: -
def isPerfectSquare(n):
"""Check if a number is a perfect square"""
i = 1
while i * i <= n:
if i * i == n:
return True
i += 1
return False
def popAndDisplay(stack):
"""Pop and display all elements from stack"""
print("Perfect square numbers in stack (popped):")
while stack:
print(stack.pop())
pushPerfectSquares(MyList, Stack)
popAndDisplay(Stack)
Output of the code: -
Perfect square numbers in stack (popped):
49
81
64
16
22
3) Aim: Write a user-defined function Large_Small() to create a stack for storing some
numbers till the user wants. Display the content of the stack along with the largest and the
smallest numbers in the stack.
[Hint: Keep popping out the elements from stack and maintain the largest and the smallest
elements retrieved so far in a variable. Repeat till stack is empty.]
Source code: -
def Large_Small():
stack = []
# Input till user wants
while True:
num = int(input("Enter a number to push into stack: "))
stack.append(num)
ch = input("Do you want to add more? (y/n): ")
if ch.lower() != 'y':
break
if not stack:
print("Stack is empty.")
return
largest = None
smallest = None
print("\nPopping elements from stack:")
while stack:
val = stack.pop()
print(val, end=" ")
if largest is None or val > largest:
largest = val
if smallest is None or val < smallest:
smallest = val
print("\nLargest number in stack:", largest)
print("Smallest number in stack:", smallest)
Large_Small()
Output of the code: -
Enter a number to push into stack: 23
Do you want to add more? (y/n): y
Enter a number to push into stack: 45
Do you want to add more? (y/n): y
Enter a number to push into stack: 98
Do you want to add more? (y/n): y
Enter a number to push into stack: 82
Do you want to add more? (y/n): y
Enter a number to push into stack: 65
Do you want to add more? (y/n): y
Enter a number to push into stack: 11
Do you want to add more? (y/n): n
24
5) Aim: Write a user-defined function def Reverse () to accept a string. Now, create a stack
using the characters (beginning to the end) from the given string. Pop out the characters from
the stack to form the reverse string. Finally, check and display whether the given string is a
Palindrome or not.
[Hint: A string is said to be a Palindrome if it is the same after reversing its characters.
For example, MALAYALAM, MADAM, NITIN, DAD, MOM, etc.]
Source code: -
def Reverse():
stack = []
s = input("Enter a string: ")
# Check palindrome
if s == rev:
print("Result: It is a Palindrome")
else:
print("Result: It is NOT a Palindrome")
25
6) Aim: Write a user-defined function def First_Last () code to push any five names in a
stack. Pop out each name from the stack, but display only those names whose first and last
characters are the same.
For example: NAMAN, ISHANI,…….
Source code: -
def First_Last():
stack = []
26
7) Aim: Write a Python code to insert the characters of a string into a queue. Frame a string
by replacing each vowel with '*' by accessing the characters from the queue. Finally, display
the original string and the modified string
Source code: -
def ReplaceVowels():
queue = []
original = input("Enter a string: ")
modified = ""
# Process queue
while queue:
ch = queue.pop(0) # dequeue (FIFO)
if ch.lower() in "aeiou":
modified += "*"
else:
modified += ch
# Display results
print("Original String :", original)
print("Modified String :", modified)
27
8) Aim: Pranay has created a dictionary containing five different car names and their prices
as key-value pairs. Write a program with separate user-defined functions to perform the
following operations:
Push the keys (car names) of the dictionary into a stack, where the corresponding
value (price) is greater than or equal to 900000.
Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
MyDict ("Maruti":750000, "Hyundai":850000, "KIA":900000,
"Honda":1050000, "Ford":1080000}
The output from the program should be: Ford: 1080000
Honda: 1050000
KIA: 900000
Source code: -
def PushStack(car_dict, stack):
# Push car names with price >= 900000
for car, price in car_dict.items():
if price >= 900000:
stack.append((car, price))
def PopStack(stack):
# Pop and display elements in LIFO order
print("Cars with price >= 900000:")
while stack:
car, price = stack.pop()
print(car, ":", price)
# -------- Main Program --------
MyDict = {
"Maruti": 750000,
"Hyundai": 850000,
"KIA": 900000,
"Honda": 1050000,
"Ford": 1080000
}
stack = []
PushStack(MyDict, stack)
PopStack(stack)
Output of the code: -
Cars with price >= 900000:
Ford : 1080000
Honda : 1050000
KIA : 900000
Conclusion: - The program was executed successfully.
28
9) Aim: Write a Python code to implement a stack to store the temperatures in degree
Celsius such that the temperature that is entered into the stack last can be accessed first.
Perform the following operations with the details given below:
I. Push(MyStack,tmp): To push the temperature (tmp) into the stack
(MyStack)
II. Peek(MyStack) : Displays the topmost temperature of the stack
III. Display(MyStack) : Displays the stack elements
Now, perform the functions Push(), Peek() and Display() using user's choice
Source code: -
def Push(MyStack, tmp):
MyStack.append(tmp)
print(f"{tmp}°C pushed into stack.")
def Peek(MyStack):
if len(MyStack) == 0:
print("Stack is empty!")
else:
print("Topmost temperature:", MyStack[-1], "°C")
def Display(MyStack):
if len(MyStack) == 0:
print("Stack is empty!")
else:
print("Stack elements (Top to Bottom):")
for i in range(len(MyStack) - 1, -1, -1):
print(MyStack[i], "°C")
MyStack = []
while True:
print("\n===== TEMPERATURE STACK MENU =====")
print("1. Push Temperature")
print("2. Peek Top Temperature")
print("3. Display Stack")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
tmp = float(input("Enter temperature in °C: "))
Push(MyStack, tmp)
else:
print("Invalid choice! Please enter 1–4.")
29
Output of the code: -
===== TEMPERATURE STACK MENU =====
1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 3
Stack is empty!
30
10) Aim: Stack is a type of linear data structure. It can store elements with the restriction that
an element can be added or removed from the top only.
Write a Python code to implement a stack to manage different city names with the details
given below:
MyStack[ ] : A stack as a list to hold the city names
MakePush(MyStack): To push a city name to the top of the stack. Display the following:
(i) Index of the topmost city
(ii) Topmost city name
(iii) All the city names of the stack
MakePop(MyStack): To remove a city name from the top of the stack, display the message
"Underflow" if the stack is empty; otherwise, display the popped-out item.
Now, perform the functions MakePush() and MakePop() as per the user's choice. Under what
principle does the above entity work?
Source code: -
def MakePush(MyStack):
city = input("Enter city name to push: ")
MyStack.append(city)
print("\n--- City Pushed Successfully ---")
print("Index of Topmost City:", len(MyStack) - 1)
print("Topmost City:", MyStack[-1])
print("All Cities in Stack:", MyStack)
def MakePop(MyStack):
if len(MyStack) == 0:
print("Underflow! Stack is empty.")
else:
removed = MyStack.pop()
print(f"Popped out city: {removed}")
while True:
print("\n===== CITY STACK MENU =====")
print("1. Push City")
print("2. Pop City")
print("3. Exit")
if choice == "1":
MakePush(MyStack)
elif choice == "2":
MakePop(MyStack)
elif choice == "3":
print("Exiting program... Goodbye!")
break
31
Output of the code: -
===== CITY STACK MENU =====
1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 2
Underflow! Stack is empty.
32
11) Aim: A Queue is an entity that enables a user to add and remove job numbers at the rear
and front ends, respectively. The details of the queue are given below:
MyQueue[ ]: a linear list as a queue to hold the job numbers, which is initially empty
Front: to point the index of the front-end element
Rear: to point the index of the rear end element
InsertQ(MyQueue): to add a job at the rear end and display all the job numbers of the queue
DeleteQ(MyQueue): deletes a job from the front end of the queue if present, otherwise
displays the message "Underflow"
a) Write a user choice program using the above functions to perform the tasks.
b) What is the common name of the entity described above?
c) State one of its applications
Source code: -
# Global variables for front and rear
front = -1
rear = -1
def InsertQ(MyQueue):
global front, rear
job = input("Enter job number to insert: ")
if front == -1: # First insertion
front = 0
rear += 1
MyQueue.append(job)
print("\n--- Job Inserted Successfully ---")
print("All Jobs in Queue:", MyQueue)
def DeleteQ(MyQueue):
global front, rear
if front == -1 or front > rear:
print("Underflow! Queue is empty.")
else:
removed = MyQueue[front]
front += 1
print(f"Deleted Job: {removed}")
while True:
print("\n===== JOB QUEUE MENU =====")
print("1. Insert Job")
print("2. Delete Job")
print("3. Exit")
if choice == "1":
InsertQ(MyQueue)
elif choice == "2":
DeleteQ(MyQueue)
elif choice == "3":
print("Exiting program... Goodbye!")
break
33
Output of the code: -
===== JOB QUEUE MENU =====
1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 2
Underflow! Queue is empty.
34
FILE HANDLING
(TEXT FILES)
1) Aim: Write a function result () to open a file 'Marks.txt' in write mode. Store the names of
the five students along with the marks secured in English, Math, and Computer Science in
this file.
Source code: -
def result():
f = open("Marks.txt", "w")
print("Enter details of 5 students:")
for i in range(5):
print("\nStudent", i + 1)
name = input("Enter Name: ")
eng = int(input("Enter English Marks: "))
maths = int(input("Enter Maths Marks: "))
cs = int(input("Enter Computer Marks: "))
def display():
try:
f = open("Marks.txt", "r")
print("📄 Contents of Marks.txt:\n")
lines = f.readlines()
for line in lines:
parts = line.strip().split()
name = parts[0]
eng = parts[1]
maths = parts[2]
cs = parts[3]
total = parts[4]
avg = parts[5]
print("Name:", name)
print("English:", eng, "Maths:", maths, "CS:", cs)
print("Total:", total, "Average:", avg)
print("-" * 30)
f.close()
except FileNotFoundError:
print("❌ File not found!")
35
# ===== MAIN PROGRAM =====
while True:
print("\n==== MENU ====")
print("1. Write Data")
print("2. Display Data")
print("3. Exit")
ch = input("Enter choice: ")
if ch == "1":
result()
elif ch == "2":
display()
elif ch == "3":
print("Program Ended.")
break
else:
print("❌ Invalid choice! Try again.")
Output of the code: -
==== MENU ====
1. Write Data
2. Display Data
3. Exit
Enter choice: 1
Enter details of 5 students:
Student 1
Enter Name: Rohan
Enter English Marks: 85
Enter Maths Marks: 90
Enter Computer Marks: 95
Student 2
Enter Name: Simran
Enter English Marks: 80
Enter Maths Marks: 70
Enter Computer Marks: 75
Student 3
Enter Name: Aarav
Enter English Marks: 88
Enter Maths Marks: 92
Enter Computer Marks: 85
Student 4
Enter Name: Neha
Enter English Marks: 95
Enter Maths Marks: 99
Enter Computer Marks: 100
Student 5
Enter Name: Karan
Enter English Marks: 60
Enter Maths Marks: 65
Enter Computer Marks: 70
36
2) Aim: Write a function display() to open the same file 'Marks.txt' in read mode which will
retrieve and display all the records available in the file 'Marks.txt.
Source code: -
def display():
try:
# Open file in read mode
f = open("Marks.txt", "r")
print("\n📄 Records in Marks.txt:\n")
lines = f.readlines()
37
3) Aim: Write a function Paragraph ( ) in Python to create a text file 'Notebook.txt' to write a
few lines into it. If you don't want to write more lines, then enter 0 (zero) to quit the function.
Source code: -
def Paragraph():
f = open("Notebook.txt", "w") # open file in write mode
print("Start writing your notebook...\n")
while True:
line = input("Enter a line: ")
f.write(line + "\n") # write line to file
f.close()
print("\n✅ All lines have been written to Notebook.txt")
38
4) Aim: Write a function Lines ( ) in Python to use the previous text file (Notebook.txt) in an
appropriate mode to retrieve all the lines. Count the number of lines available in the file and
display all the lines with the line number
Source code: -
def Lines():
# Open Notebook.txt in read mode
f = open("Notebook.txt", "r")
i = 1
for line in lines:
print("Line", i, ":", line.strip())
i += 1
print("-" * 50)
39
5) Aim: Write a function Contact() in Python to create a text file 'Phone.txt' to write the
names of five people along with their contact numbers.
Source code: -
📱 Enter details of 5 people:
Person 1
Enter Name: Rohan
Enter Contact Number: 9876543210
----------------------------------------
Person 2
Enter Name: Priya
Enter Contact Number: 9123456789
----------------------------------------
Person 3
Enter Name: Aman
Enter Contact Number: 9090909090
----------------------------------------
Person 4
Enter Name: Neha
Enter Contact Number: 8888888888
----------------------------------------
Person 5
Enter Name: Suresh
Enter Contact Number: 7777777777
----------------------------------------
Person 1
Enter Name: David
Enter Contact Number: 9876543210
----------------------------------------
Person 2
Enter Name: Ramesh
Enter Contact Number: 9123456789
----------------------------------------
Person 3
Enter Name: Deepak
Enter Contact Number: 9090909090
----------------------------------------
Person 4
Enter Name: Neha
Enter Contact Number: 8888888888
----------------------------------------
Person 5
Enter Name: Divya
Enter Contact Number: 7777777777
----------------------------------------
40
In Phone.txt file will contain:
David 9876543210
Ramesh 9123456789
Deepak 9090909090
Neha 8888888888
Divya 7777777777
41
6) Aim: A file 'Phone.txt' is a text file that contains a few names of the consumers. Write a
function Display ( ) in Python to open the file in an appropriate mode to retrieve the names.
Count and display the names of all the consumers with the phone numbers whose names start
with the letter 'D'. Assume that the file already exists in the system
Source code: -
def Display():
# Open the file in read mode
f = open("Phone.txt", "r")
count = 0
for line in f:
line = line.strip() # remove \n
if line != "": # skip empty lines
parts = line.split(" ", 1) # split into name and number
name = parts[0]
phone = parts[1] if len(parts) > 1 else "N/A"
print("-" * 50)
print("Total consumers with names starting with 'D':", count)
f.close()
42
7) Aim: A file 'Phone.txt' is a text file that contains a few names of the consumers. Write a
function Display ( ) in Python to open the file in an appropriate mode to retrieve the names.
Count and display the names of all the consumers with the phone numbers whose names start
with the letter 'D'. Assume that the file already exists in the system
Source code: -
def Add_Name():
print("=== Add New Students to Admission.txt ===")
while True:
name = input("Enter student name (or 0 to quit): ")
if name == "0":
print("✅ No more names to add. File updated successfully.")
break
else:
file.write(name + "\n")
print(f"✔ {name} added to Admission.txt")
file.close()
print("=== Process Completed ===")
43
8) Aim: The file 'Admission.txt' contains the names of all the students who have been
admitted to the 'Science' and 'Commerce' streams of class XI. Write a function Shift_Name()
in Python to copy the names of the students of the 'Science' stream to another text file,
'Science.txt', from the 'Admission.txt' file. Finally, all the records of the file 'Science.txt' are
displayed.
Source code: -
def Shift_Name():
print("=== Copying Science Stream Students ===")
file_in.close()
file_out.close()
44
9) Aim: Write a function Tabulation() to open a file "Result.txt" in "w+" mode to store the
index number, name, and marks of a few students. The number of records to be entered into
the file will be based on the user's choice. Use the same file (without reopening) to retrieve
its records and display them on the screen.
Source code: -
def Tabulation():
print("=== Student Result Entry ===")
# open file in w+ mode (write + read)
f = open("Result.txt", "w+")
# ask how many students to enter
n = int(input("Enter number of students: "))
# write records into file
for i in range(n):
print(f"\n--- Enter record for student {i + 1} ---")
index = input("Enter Index Number: ")
name = input("Enter Name: ")
marks = input("Enter Marks: ")
Source code: -
def Sale():
print("=== Product Sale Records ===")
f = open("Product.txt", "r+")
f.seek(0)
lines = f.readlines()
f.seek(0)
print("\n--- Updated Records in Product.txt ---")
print("{:<10}{:<10}{:<10}{:<10}".format("Code", "Qty", "Price", "Total"))
all_lines = f.readlines()
for line in all_lines:
data = line.strip().split()
if len(data) == 4:
print("{:<10}{:<10}{:<10}{:<10}".format(data[0], data[1], data[2],
data[3]))
f.close()
print("\n=== Process Completed ===")
46
Output of the code: -
47
11) Aim: A file "IPL_Champ" is created to contain the names of the IPL teams along with
the years in which they were champions. Define a function Cricket() to use the file in "a+"
mode to add a few more records to the file. Finally, use the same file without re-opening it to
retrieve the records and display them on the screen.
Source code: -
def Cricket():
print("=== IPL Champion Records ===")
48
Conclusion: - The program was executed successfully.
FILE HANDLING
(BINARY FILES)
1) Aim: Write a Python code to store some integer numbers as a list element in the binary
file 'Number.dat' till the user wants. Finally, open the file in appropriate mode to retrieve and
display the elements.
Source code: -
import pickle
def NumberFile():
# Open the file in write+binary mode
with open("Number.dat", "wb") as f:
numbers = []
while True:
num = int(input("Enter an integer number: "))
numbers.append(num)
more = input("Do you want to add more numbers? (y/n): ")
if more.lower() != 'y': break
# dump the entire list into the binary file
pickle.dump(numbers, f)
print("\nNumbers successfully stored in Number.dat!\n")
# Now open the same file in read+binary mode
with open("Number.dat", "rb") as f:
stored_numbers = pickle.load(f)
print("Numbers retrieved from Number.dat are:")
for i, n in enumerate(stored_numbers, start=1):
print(f"{i}. {n}")
# Call the function
NumberFile()
49
Conclusion: - The program was executed successfully.
2) Aim: Write a function def Display() in Python which reads the integer elements from the
previously created binary file 'Number.dat'. Display only those numbers that are either
divisible by 7 or end with the digit 7.
Source code: -
import pickle
def Display():
found = False
for n in numbers:
if n % 7 == 0 or str(n).endswith('7'):
print(n)
found = True
if not found:
print("No such numbers found.")
Display()
77
42
27
127
50
3) Aim: The file 'Prize.dat' contains the records comprising Name, Class, and Rank of all the
'Prize Winners' of class XII students. Write a function def Prize_Winners() in Python to
display all the names along with the Class and Rank, who have secured 'Rank' as 1 (One) in
the format shown below:
Name Class Rank
………. ……….. ………….
………. ……….. ………….
[Assume that the file is already present in the hard disk.]
Source code: -
import pickle
def Prize_Winners():
f = open("Prize.dat", "rb")
print("{:<15} {:<10} {:<5}".format("Name", "Class", "Rank"))
print("-" * 35)
while True:
try:
name, clas, rank = pickle.load(f)
if rank == 1:
print("{:<15} {:<10} {:<5}".format(name, clas, rank))
except EOFError:
break
f.close()
# Call function
Prize_Winners()
51
4) Aim: The file 'Number.dat' contains some integer numbers. Write a function def
Conversion () in Python to display the binary and octal equivalent of all the numbers.
[Assume that the file is already present in the hard disk.]
Source code: -
import pickle
def Conversion():
f = open("Number.dat", "rb")
numbers = pickle.load(f) # assuming numbers are stored as a list
f.close()
# Example call
Conversion()
52
5) Aim: Write a Python code to accept an integer number. Pass it to a function that returns
the number of factors. Finally, display whether the number is a prime number or not.
[Hint: A number of said to be a prime number if it has only two factors.]
Source code: -
import pickle
def Count():
f = open("Name.dat", "rb")
names = pickle.load(f) # assuming file stores a list of names
f.close()
# Example call
Count()
53
6) Aim: A file 'State.dat' contains a list of Indian states with their capitals. Write a function
def State_Cap() in Python to display all the states along with capitals whose state name starts
with a consonant.
[Assume that the file is already present in the hard disk.]
Source code: -
import pickle
def State_Cap():
f = open("State.dat", "rb")
states = pickle.load(f) # assuming list of tuples [(state, capital), ...]
f.close()
# Example call
State_Cap()
54
7) Aim: A binary file 'Result.dat' contains the records (each containing names and marks in
English, Maths, and Computer Science) of all the students of class XII. Write a function def
Result () in Python to display the names of all the students who have secured 90% and above
in English, Maths, and Computer Science.
[Assume that the file is already present in the hard disk.]
Source code: -
import pickle
def Result():
f = open("Result.dat", "rb")
data = pickle.load(f) # assuming list of tuples: [(name, eng, maths, cs), ...]
f.close()
# Example call
Result()
55
8) Aim: The librarian keeps the record (index number and names) of all the books of class
XI-XII in the file 'Library.dat'. Write a function def Book() in Python to add few more books
in the file 'Library.dat' to keep the records updated.
[Assume that the file is already present in the system.]
Source code: -
import pickle
def Book():
f = open("Library.dat", "ab") # open in append-binary mode
f.close()
56
9) Aim: Write a function def Phone Name() in Python to search a name in the file
'Contact.dat' (each record contains a single name). If the name is found then display 'The
record is found', otherwise display 'No such name is available in the file.
[Assume that the file is already present in the hard disk.]
Source code: -
import pickle
def PhoneName():
f = open("Contact.dat", "rb") # open in read-binary mode
search_name = input("Enter the name to search: ")
found = False
try:
while True:
name = pickle.load(f) # read each record
if name == search_name:
print("The record is found")
found = True
break
except EOFError:
pass
f.close()
if not found:
print("No such name is available in the file.")
57
FILE HANDLING
(CSV FILES)
1)Aim: Write a Python code to create a file 'Holiday.csv' to keep the records of holiday
package trips for different places with their tariffs. The format is as shown below:
Type Trip Days Tour Cost
A01 Delhi-Agra 2 5000
A02 Delhi-Goa 3 8000
…… ………….. …… ……...
…… …………... …… ……...
Source code: -
import csv
writer = csv.writer(f)
# Write header
for i in range(n):
58
Output of the code: -
Enter number of holiday packages: 8
59
2) Aim: Write a function def Trip() in Python to read all the records of the file 'Holiday. csv'
(created in the previous question) and display the details of holiday package trips for
different places with their tariffs.
For example:
Type Trip Days Tour Cost
A01 Delhi-Agra 2 5000
A02 Delhi-Goa 3 8000
…… ………….. …… ……...
…… …………... …… ……...
[Assume that the file is already present in the hard disk.]
Source code: -
import csv
def Trip():
with open("Holiday.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Read header row
print(f"{header[0]:<8}{header[1]:<20}{header[2]:<10}{header[3]:<10}")
print("-"*50)
60
3) Aim: Write a function def Salary() in Python to read all the records from an existing file
'Employee.csv' which stores the records of the employees under different fields as mentioned
below:
For example:
Emp_Code Name Grade Salary
E/01 Anand Mishra SP4 45000
E/02 Ramesh Shukla SP3 41000
E/03 Pushkar Jain SP2 38000
…… ………….. …… ……...
…… …………... …… ……...
Now, display the records of all those employees whose salary is 40,000 or more.
[Assume that the file is already present in the hard disk.]
Source code: -
import csv
def Salary():
61
4) Aim: Write a function def Display() in Python to read all the records from the file
'Inventory.csv' which stores the records of various products such as Television, Refrigerator,
Air-Conditioner, etc. under different fields as mentioned below:
Code Item Company Price Quantity
T/01 Television LG 42000 15
T/02 Television Sony 45000 20
F/01 Refrigerator LG 35000 10
……. ……………. ………. ……… …….
Now, display the details of all televisions of various companies from the file.
[Assume that the file is already present in the hard disk.]
Source code: -
import csv
def Display():
with open("Inventory.csv", "r") as fr:
reader = csv.reader(fr)
header = next(reader) # skip header
print(f"{'Code':<6} {'Item':<12} {'Company':<10} {'Price':<8} {'Quantity':<8}")
print("-"*50)
for a in reader:
if a[1] == "Television":
print(f"{a[0]:<6} {a[1]:<12} {a[2]:<10} {a[3]:<8} {a[4]:<8}")
# main program
Display()
62
5) Aim: under different fields as mentioned below: Write a function def Min Fee() in Python
to read all the records from the file 'Professional.csv', which stores the records of various
professional courses
Code Course Name Qualification Fee Duration
B/01 BCA Intermediate 900000 4 Years
C/01 CSE Intermediate 850000 4 Years
L/01 LLB Intermediate 700000 3 Years
B/02 BBA Intermediate 750000 3 Years
…….. …………… …………….. ……… ……….
Now, display the record from the file whose course fee is the lowest.
[Assume that the file is already present in the hard disk.]
Source code: -
import csv
def MinFee():
with open("Professional.csv", mode="r") as file:
reader = csv.DictReader(file)
records = list(reader)
# Call function
MinFee()
63
6) Aim: The file 'InterSchool_Sports.csv' keeps the records of the number of medals won by
each school in the Inter School Sports Meet. Write a function def Medals() in Python to read
the records and display the total number of medals won by a particular school.
The different fields are as shown below:
School Name Gold Silver Bronze
Valley Green 1 2 4
Hill View 3 5 7
Blue Bells 2 8 6
Green Bird 4 11 8
The user enters the name of a school to display the total number of medals won, if the name
doesn't exist then it displays an appropriate message.
[Assume that the file is already present in the hard disk.]
Source code: -
import csv
def Medals():
school_name = input("Enter School Name: ")
with open("InterSchool_Sports.csv", mode="r") as file:
reader = csv.DictReader(file)
found = False
if not found:
print("School not found in the records.")
def Participate():
# open file in append mode so new records are added at the end
with open("Quiz.csv", mode="a", newline="") as file:
writer = csv.writer(file)
for i in range(n):
print(f"\nEnter details for School {i+1}:")
school = input("School Name: ")
name1 = input("Name 1: ")
class1 = input("Class of Name 1: ")
name2 = input("Name 2: ")
class2 = input("Class of Name 2: ")
1)Aim: Write a Python code to assign three different values to the separate variables such
that:
i. First number is in the decimal number system (base 10).
ii. The second number is in the octal number system ("00").
iii. The third number is in the hexadecimal number system ("0x").
Now, convert all of them into the binary number system and display the result.
Source code: -
# Assign values
decimal_num = 25 # Decimal (base 10)
66
2) Aim: Write a Python code to assign three different values to the separate variables such
that:
(i) The first number is in a binary number system.
(ii) The second number is in the octal number system ("00").
(iii) The third number is in the hexadecimal number system ("0x").
Now, convert all of them into their decimal number system equivalents (base 10) and display
the result.
Source code: -
# Assign values
binary_num = 0b10101 # Binary (base 2) -> decimal 21
Binary to Decimal : 21
Octal to Decimal : 21
Hexadecimal to Decimal: 21
67
3) Aim: Write a Python code to assign three different values to the corresponding variables
such that the:
i. The first number is in the decimal number system.
ii. The second number is in the binary number system ("0b").
iii. The third number is in the hexadecimal number system ("0x").
Now, convert all of them into their octal number system equivalents (base 8) and display the
result.
Source code: -
# Assign values
decimal_num = 100 # Decimal (base 10)
68
4) Aim: In tossing a coin, you want to know the number of times you get 'Head' and 'Tail'.
You keep the record as '1' (one) for getting 'Head' and '0' (Zero) for 'Tail'. Write a Python
code to perform the above task, assuming you have tossed a coin 20 times in this game.
Source code: -
import random
69
Structured Query Language
(SQL)
Aim: Write SQL commands to create a table and insert records into it.
Source code: -
mysql> CREATE DATABASE School;
Query OK, 1 row affected (0.01 sec)
70
2) Aim: Write SQL commands to retrieve data using the SELECT clause.
Source code: -
-- Show all records
SELECT * FROM health_drink;
71
3) Aim: Write SQL queries to retrieve data from the table using the ORDER BY Clause
Source code: -
-- Order records by Price in ascending order
SELECT * FROM health_drink ORDER BY Price ASC;
73
5) Aim: Write SQL queries to retrieve data from the table using the GROUP BY clause
with the HAVING condition.
Source code: -
-- Brands having more than 2 products
SELECT Name, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Name
HAVING COUNT(*) > 2;
74
6) Aim: Write SQL queries to retrieve data from the table using the WHERE clause with the
LIKE operator.
Source code: -
-- Name starts with 'B'
SELECT * FROM health_drink
WHERE Name LIKE 'B%';
# establish connection
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147", # your password
database="ujjwal" # make sure database exists
)
cur = mydb.cursor()
78
2) Aim: Write a Python program to insert records into the table using MySQL–Python
interface.
Source code: -
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="1147",
database="ujjwal"
)
cursor = conn.cursor()
# Insert records
records = [
(1, 'Bournvita', 'Plain', 'B1', 100, 80, 130, 440),
(2, 'Bournvita', 'Choco', 'B1', 160, 80, 200, 440),
(3, 'Horlicks', 'Plain', 'H1', 100, 320, 150, 450),
(4, 'Horlicks', 'Choco', 'H1', 120, 350, 180, 450),
(5, 'Ensure', 'Plain', 'E1', 100, 450, 210, 650),
(6, 'Ensure', 'Choco', 'E1', 140, 500, 230, 650),
(7, 'Complan', 'Plain', 'C1', 100, 400, 140, 350),
(8, 'Complan', 'Choco', 'C1', 150, 420, 160, 350),
(9, 'Complan', 'Plain', 'C1', 170, 380, 140, 350)
]
query = """
INSERT INTO health_drink
(No, Name, Title, Code, Qty, Price, Vitamin, Calcium)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
cursor.executemany(query, records)
# Commit changes
conn.commit()
# Close connection
cursor.close()
conn.close()
Output of the code: -
+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 1 | Bournvita | Plain | B1 | 100 | 80 | 130 | 440 |
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
| 3 | Horlicks | Plain | H1 | 100 | 320 | 150 | 450 |
| 4 | Horlicks | Choco | H1 | 120 | 350 | 180 | 450 |
| 5 | Ensure | Plain | E1 | 100 | 450 | 210 | 650 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
+----+-----------+-------+------+-----+-------+---------+---------+
Source code: -
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="1147",
database="ujjwal"
)
cursor = conn.cursor()
# Close connection
cursor.close()
conn.close()
4) Aim: To write a Python program to interface with MySQL and update records in a table.
80
Source code: -
import mysql.connector as mycon
# connect to database
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147",
database="ujjwal" # database is 'ujjwal'
)
cur = mydb.cursor()
mydb.commit()
+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 1 | Bournvita | Plain | B1 | 100 | 90 | 130 | 440 |
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
| 3 | Horlicks | Plain | H1 | 100 | 320 | 150 | 450 |
| 4 | Horlicks | Choco | H1 | 120 | 350 | 180 | 450 |
| 5 | Ensure | Plain | E1 | 100 | 450 | 210 | 650 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
+----+-----------+-------+------+-----+-------+---------+---------+
81
5) Aim: To write a Python program to interface with MySQL and delete a record from a
table.
Source code: -
import mysql.connector as mycon
# connect to database
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147",
database="ujjwal" # database name
)
cur = mydb.cursor()
mydb.commit()
82
6) Aim: To write a Python program to create a new table and insert records into it using a
Parameterized Query.
Source code: -
import mysql.connector as mycon
# connect to database
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147",
database="ujjwal" # use your database
)
cur = mydb.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS sports (
ID INT PRIMARY KEY AUTO_INCREMENT,
PlayerName VARCHAR(50),
Game VARCHAR(30),
Score INT
)
""")
print("Table created successfully!")
insert_query = "INSERT INTO sports (PlayerName, Game, Score) VALUES (%s, %s, %s)"
for i in range(n):
print(f"\nRecord {i+1}:")
name = input("Enter Player Name: ")
game = input("Enter Game: ")
score = int(input("Enter Score: "))
# Commit changes
mydb.commit()
# Close connection
cur.close()
mydb.close()
83
Output of the code: -
In Python:
Record 1:
Enter Player Name: Amit
Enter Game: Cricket
Enter Score: 80
Record 2:
Enter Player Name: Riya
Enter Game: Football
Enter Score: 65
Record 3:
Enter Player Name: Sneha
Enter Game: Tennis
Enter Score: 40
Record 4:
Enter Player Name: Mohit
Enter Game: Badminton
Enter Score: 55
In MySQL:
+----+------------+-----------+-------+
| ID | PlayerName | Game | Score |
+----+------------+-----------+-------+
| 1 | Amit | Cricket | 80 |
| 2 | Riya | Football | 65 |
| 3 | Sneha | Tennis | 40 |
| 4 | Mohit | Badminton | 55 |
+----+------------+-----------+-------+
84
7) Aim: Write a Python program to interface with MySQL and retrieve records from the
table using a parameterized query with the WHERE clause.
Source code: -
import mysql.connector as mycon
# Connect to database
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147",
database="ujjwal"
)
cur = mydb.cursor()
cur.execute(select_query, (game,))
# Close connection
cur.close()
mydb.close()
85