0% found this document useful (0 votes)
4 views85 pages

Computer Science Journal

The document outlines various Python programming tasks involving functions and recursion, including calculating factors, HCF, LCM, Fibonacci series, palindrome checks, sorting, vowel counting, and more. Each task includes a specific aim, source code, sample input/output, and a conclusion stating successful execution. The document serves as a comprehensive guide for implementing these programming concepts in Python.
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)
4 views85 pages

Computer Science Journal

The document outlines various Python programming tasks involving functions and recursion, including calculating factors, HCF, LCM, Fibonacci series, palindrome checks, sorting, vowel counting, and more. Each task includes a specific aim, source code, sample input/output, and a conclusion stating successful execution. The document serves as a comprehensive guide for implementing these programming concepts in Python.
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/ 85

Functions & recursion

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

# Step 1: Accept input


num = int(input("Enter an integer: "))

# Step 2: Call the function


factors = count_factors(num)

# Step 3: Display results


print(f"Number of factors of {num} = {factors}")

if factors == 2:
print(f"{num} is a Prime Number ✅")
else:
print(f"{num} is NOT a Prime Number ❌")

Output of the code: -


Enter an integer: 7
Number of factors of 7 = 2
7 is a Prime Number ✅

Conclusion: - The program was executed successfully.

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

# Step 1: Accept input


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Step 2: Call the function for HCF


hcf = find_hcf(num1, num2)

# Step 3: Calculate LCM using formula


lcm = (num1 * num2) // hcf

# Step 4: Display results


print(f"HCF of {num1} and {num2} = {hcf}")
print(f"LCM of {num1} and {num2} = {lcm}")

Output of code: -

Enter first number: 12


Enter second number: 18
HCF of 12 and 18 = 6
LCM of 12 and 18 = 36

Conclusion: - The program was executed successfully

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

Enter the employee's name: Amit Jaiswal


Enter the basic salary of the employee: 52000
Employee Name: Amit Jaiswal
Gross Salary: 76960.00
Net Salary: 70460.00

Conclusion: - The program was executed successfully.

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]

Conclusion: - The program was executed successfully.

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

Enter a word: MALAYALAM


Palindrome Word

Conclusion: - The program was executed successfully.

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

Enter a word in lowercase: computer


Word in alphabetical order: cemoprtu

Conclusion: - The program was executed successfully.

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

Enter a word/string: Computer Science


No. of vowels = 6

Conclusion: - The program was executed successfully.

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

print("Original List:", names_list)

sorted_names = bubble_sort(names_list)

print("Arranged Names (Alphabetical Order):", sorted_names)

Output of code: -

Original List: ['Sanjay', 'Amit', 'Kiran', 'Zoya', 'Priya', 'Deepak']


Arranged Names (Alphabetical Order): ['Amit', 'Deepak', 'Kiran', 'Priya', 'Sanjay',
'Zoya']

Conclusion: - The program was executed successfully.

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

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return True
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return False

# Main Program
# Step 1: Accept list of integers
numbers = list(map(int, input("Enter integers separated by space: ").split()))

# Step 2: Sort list for binary search


numbers.sort()

# Step 3: Accept number to search


num = int(input("Enter a number to search: "))

# Step 4: Call function


if binary_search(numbers_

Output of code: -

Enter integers separated by space: 12 5 7 20 15 3 10


Enter a number to search: 15
Number is Present

Conclusion: - The program was executed successfully.

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

# Call the function


display_vowel_words(words_tuple)

Output of code: -

Enter words in lowercase separated by space: apple orange banana mango umbrella cat
Words starting with a vowel:
apple
orange
umbrella

Conclusion: - The program was executed successfully.

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

result = power(base, index)


print(base, "raised to", index, "=", result)

Output of the code: -


Enter a base number: 5
Enter index: 4
5 raised to 4 = 625

Conclusion: - The program was executed successfully.

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)

Output of the code: -


Enter a number: 10
Sum of odd numbers from 1 to 10 = 25

Conclusion: - The program was executed successfully.

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)

print("Sum of the digits:", result)

Output of the code: -


Enter an integer: 7
Number of factors of 7 = 2
7 is a Prime Number ✅

Conclusion: - The program was executed successfully.

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)

print("Sum of the digits:", result)

Output of the code: -


Enter a number: 348
Sum of the digits: 15

Conclusion: - The program was executed successfully.

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)

Output of the code: -


Enter a number: 247
Reversed Number: 742

Conclusion: - The program was executed successfully.

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)

Output of the code: -


Enter a word: COMPUTER
The reverse word: RETUPMOC

Conclusion: - The program was executed successfully.

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)

Output of the code: -


Enter a string: Computer Science
Number of vowels = 6

Conclusion: - The program was executed successfully.

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)

Output of the code: -


Enter a number: 153
153 is an Armstrong number

Conclusion: - The program was executed successfully.

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

Output of the code: -


Largest element: 99

Conclusion: - The program was executed successfully.

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

mid = (low + high) // 2

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

for n in nums: # converting manually instead of using map


lst.append(int(n))

lst.sort() # Binary Search requires sorted list


print("Sorted list:", lst)

key = int(input("Enter the number to search: "))

if binary_search(lst, 0, len(lst) - 1, key):


print("Number is present")
else:
print("Number is not present")

Output of the code: -


Enter numbers separated by spaces: 42 15 67 23 99 51
Sorted list: [15, 23, 42, 51, 67, 99]
Enter the number to search: 67
Number is present

Conclusion: - The program was executed successfully.

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)

# Insert another number


num = int(input("Enter a number to insert: "))
queue.append(num)

# Count frequency of num ONLY in the original elements


original_size = 5 # we know we took 5 numbers first
count = 0

print("\nElements in the queue:")


size_now = len(queue) # should be 6
for i in range(size_now):
val = queue.pop(0) # dequeue
print(val, end=" ")
if i < original_size and val == num: # exclude the inserted one
count += 1
queue.append(val) # enqueue back to preserve order

print("\n\nFrequency of", num, "=", count)

# ---- main ----


frequency_in_queue()
Output of the code: -
Enter 5 integers:
Enter number 1: 23
Enter number 2: 44
Enter number 3: 51
Enter number 4: 44
Enter number 5: 65
Enter a number to insert: 44
Elements in the queue:
23 44 51 44 65 44
Frequency of 44 = 2

Conclusion: - The program was executed successfully.

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 pushPerfectSquares(mylist, stack):


"""Push perfect squares from list to stack"""
for num in mylist:
if isPerfectSquare(num):
stack.append(num)

def popAndDisplay(stack):
"""Pop and display all elements from stack"""
print("Perfect square numbers in stack (popped):")
while stack:
print(stack.pop())

# ---- Main Program ----


MyList = [16, 44, 55, 64, 80, 81, 49, 66, 99, 75]
Stack = []

pushPerfectSquares(MyList, Stack)
popAndDisplay(Stack)
Output of the code: -
Perfect square numbers in stack (popped):
49
81
64
16

Conclusion: - The program was executed successfully.

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)

# ---- main ----

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

Popping elements from stack:


11 65 82 98 45 23
Largest number in stack: 98
Smallest number in stack: 11

Conclusion: - The program was executed successfully.


23
4) Aim: Write a user-defined function def Vowels() to input a string using a stack. Keep
popping out each element from the stack, and if it is a vowel, then display; otherwise, ignore.
Sample Input: Information
Sample Output: o
i
a
o
I
Source code: -
def Vowels():
stack = []
s = input("Enter a string: ")

# Push all characters into the stack


for ch in s:
stack.append(ch)

print("\nVowels in reverse order (from stack):")


# Pop and check vowels
while stack:
val = stack.pop()
if val.lower() in "aeiou":
print(val)

# ---- main ----


Vowels()

Output of the code: -


Enter a string: Information

Vowels in reverse order (from stack):


o
i
a
o
I

Conclusion: - The program was executed successfully.

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

# Push all characters into stack


for ch in s:
stack.append(ch)

# Pop characters to form reversed string


rev = ""
while stack:
rev += stack.pop()

print("\nOriginal String :", s)


print("Reversed String :", rev)

# Check palindrome
if s == rev:
print("Result: It is a Palindrome")
else:
print("Result: It is NOT a Palindrome")

# ---- main ----


Reverse()

Output of the code: -


Enter a string: MADAM

Original String: MADAM


Reversed String: MADAM
Result: It is a Palindrome

Conclusion: - The program was executed successfully.

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 = []

# Push 5 names into stack


for i in range(5):
name = input(f"Enter name {i+1}: ")
stack.append(name)

print("\nNames with same first and last character:")

# Pop from stack and check


while stack:
name = stack.pop()
if name[0].lower() == name[-1].lower(): # case-insensitive check
print(name)

# ---- main ----


First_Last()

Output of the code: -


Enter name 1: NAMAN
Enter name 2: ISHANI
Enter name 3: RAJ
Enter name 4: ANNA
Enter name 5: AJAYA

Names with the same first and last character:


AJAYA
ANNA
NAMAN

Conclusion: - The program was executed successfully.

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

# Insert characters into queue


for ch in original:
queue.append(ch)

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)

# ---- main ----


ReplaceVowels()

Output of the code: -


Enter a string: Information
Original String: Information
Modified String: *nf*rm*t**n

Conclusion: - The program was executed successfully.

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

# -------- Main Program --------

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)

elif choice == "2":


Peek(MyStack)

elif choice == "3":


Display(MyStack)

elif choice == "4":


print("Exiting program... Goodbye!")
break

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!

===== TEMPERATURE STACK MENU =====


1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 1
Enter temperature in °C: 34
34.0°C pushed into stack.

===== TEMPERATURE STACK MENU =====


1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 1
Enter temperature in °C: 42
42.0°C pushed into stack.

===== TEMPERATURE STACK MENU =====


1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 2
Topmost temperature: 42.0 °C

===== TEMPERATURE STACK MENU =====


1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 3
Stack elements (Top to Bottom):
42.0 °C
34.0 °C

===== TEMPERATURE STACK MENU =====


1. Push Temperature
2. Peek Top Temperature
3. Display Stack
4. Exit
Enter your choice (1-4): 4
Exiting program... Goodbye!

Conclusion: - The program was executed successfully.

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

# -------- Main Program --------


MyStack = []

while True:
print("\n===== CITY STACK MENU =====")
print("1. Push City")
print("2. Pop City")
print("3. Exit")

choice = input("Enter your choice (1-3): ")

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.

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 1
Enter city name to push: Delhi
--- City Pushed Successfully ---
Index of Topmost City: 0
Topmost City: Delhi
All Cities in Stack: ['Delhi']

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 1
Enter city name to push: Kolkata
--- City Pushed Successfully ---
Index of Topmost City: 1
Topmost City: Kolkata
All Cities in Stack: ['Delhi', 'Kolkata']

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 2
Popped out city: Kolkata

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 2
Popped out city: Delhi

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 2
Underflow! Stack is empty.

===== CITY STACK MENU =====


1. Push City
2. Pop City
3. Exit
Enter your choice (1-3): 3
Exiting program... Goodbye!

Conclusion: - The program was executed successfully.

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

# -------- Main Program --------


MyQueue = []

while True:
print("\n===== JOB QUEUE MENU =====")
print("1. Insert Job")
print("2. Delete Job")
print("3. Exit")

choice = input("Enter your choice (1-3): ")

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.

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 1
Enter job number to insert: P001

--- Job Inserted Successfully ---


All Jobs in Queue: ['P001']

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 1
Enter job number to insert: K001

--- Job Inserted Successfully ---


All Jobs in Queue: ['P001', 'K001']

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 2
Deleted Job: P001

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 2
Deleted Job: K001

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 2
Underflow! Queue is empty.

===== JOB QUEUE MENU =====


1. Insert Job
2. Delete Job
3. Exit
Enter your choice (1-3): 3
Exiting program... Goodbye!

Conclusion: - The program was executed successfully.

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

# Open file in write mode

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

total = eng + maths + cs


avg = total / 3

# Write into file

f.write(name + " " + str(eng) + " " + str(maths) + " " +


str(cs) + " " + str(total) + " " + str(avg) + "\n")
f.close()
print("\n✅ Data successfully written into Marks.txt\n")

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

✅ Data successfully written into Marks.txt


Conclusion: - The program was executed successfully.

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

# अगर file खाली है


if not lines:
print("⚠️ No records found in file!")
else:
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 'Marks.txt' not found!")

Output of the code: -


Riya 85 90 88
Aarav 78 82 80
Neha 92 95 94
Raj 65 70 75
Meena 88 85 90

Conclusion: - The program was executed successfully.

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

choice = input("Do you want to continue? (yes/no): ").lower()


if choice == "no" or choice == "n":
break

f.close()
print("\n✅ All lines have been written to Notebook.txt")

# Call the function


Paragraph()

Output of the code: -


Enter a line: Python is fun
Do you want to continue? (yes/no): y
Enter a line: I like coding
Do you want to continue? (yes/no): y
Enter a line: Notebook is working
Do you want to continue? (yes/no): n

✅ All lines have been written to Notebook.txt

In Notebook.txt file will contain:


Python is fun
I like coding
Notebook is working

Conclusion: - The program was executed successfully.

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

# Read all lines


lines = f.readlines()

# Close the file


f.close()

# Count and display


count = len(lines)
print("Total number of lines in Notebook.txt:", count)
print("-" * 50)

i = 1
for line in lines:
print("Line", i, ":", line.strip())
i += 1

print("-" * 50)

# ---- call the function ----


Lines()

Output of the code: -


Total number of lines in Notebook.txt: 3
--------------------------------------------------
Line 1 : Python is fun
Line 2 : I like coding
Line 3 : Notebook is working
--------------------------------------------------

Conclusion: - The program was executed successfully.

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

✅ Data successfully written into Phone.txt


Output of the code: -
📱 Enter details of 5 people:

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

✅ Data successfully written into Phone.txt

40
In Phone.txt file will contain:
David 9876543210
Ramesh 9123456789
Deepak 9090909090
Neha 8888888888
Divya 7777777777

Conclusion: - The program was executed successfully.

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

print("Consumers whose names start with 'D':")


print("-" * 50)

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"

if name.upper().startswith("D"): # check if starts with D


count += 1
print(f"{count}. {name} - {phone}")

print("-" * 50)
print("Total consumers with names starting with 'D':", count)

f.close()

# ===== MAIN PROGRAM =====


Display()

Output of the code: -


Consumers whose names start with 'D':
--------------------------------------------------
1. David - 9876543210
2. Deepak - 9090909090
3. Divya - 7777777777
--------------------------------------------------
Total consumers with names starting with 'D': 3

Conclusion: - The program was executed successfully.

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

file = open("Admission.txt", "a") # open file in append mode

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

Output of the code: -


=== Add New Students to Admission.txt ===
Enter student name (or 0 to quit): Aarav
✔ Aarav added to Admission.txt
Enter student name (or 0 to quit): Priya
✔ Priya added to Admission.txt
Enter student name (or 0 to quit): Rohan
✔ Rohan added to Admission.txt
Enter student name (or 0 to quit): Sneha
✔ Sneha added to Admission.txt
Enter student name (or 0 to quit): Dev
✔ Dev added to Admission.txt
Enter student name (or 0 to quit): 0
✅ No more names to add. File updated successfully.
=== Process Completed ===

In 📂 Final content of Admission.txt:


Aarav
Priya
Rohan
Sneha
Dev

Conclusion: - The program was executed successfully.

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

# open Admission.txt in read mode


file_in = open("Admission.txt", "r")

# open Science.txt in write mode


file_out = open("Science.txt", "w")

# read all lines from Admission.txt


lines = file_in.readlines()

count = 0 # to count how many students copied

# check each line for 'Science'


for line in lines:
if "Science" in line:
file_out.write(line)
count += 1

file_in.close()
file_out.close()

print(f"✔ {count} students copied to Science.txt\n")

# display all records from Science.txt


print("=== Science.txt Records ===")
file_out = open("Science.txt", "r")
records = file_out.readlines()
for rec in records:
print(rec.strip())
file_out.close()
print("=== Process Completed ===")

Output of the code: -


=== Copying Science Stream Students ===
✔ 3 students copied to Science.txt

=== Science.txt Records ===


A001 Akash Gupta Science
A004 Dipayan Das Science
A005 Vimal Kishore Science
=== Process Completed ===

Conclusion: - The program was executed successfully.

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

record = index + " " + name + " " + marks + "\n"


f.write(record)
# move file pointer to the beginning
f.seek(0)
print("\n=== Records in Result.txt ===")
lines = f.readlines()
for line in lines:
print(line.strip())
f.close()
print("=== Process Completed ===")

Output of the code: -


=== Student Result Entry ===
Enter number of students: 3

--- Enter record for student 1 ---


Enter Index Number: A001
Enter Name: Ramesh
Enter Marks: 85

--- Enter record for student 2 ---


Enter Index Number: A002
Enter Name: Suresh
Enter Marks: 92

--- Enter record for student 3 ---


Enter Index Number: A003
Enter Name: Neha
Enter Marks: 78

=== Records in Result.txt ===


A001 Ramesh 85
A002 Suresh 92
A003 Neha 78
=== Process Completed ===

Conclusion: - The program was executed successfully.


45
10) Aim: A file "Product.txt" has already been created with the record containing code
quantity, price and total amount. Define a function Sale() to open the file int mode to read
and display its records. Add some more records into the file without re-opening it in append
mode. Finally, display all the records of the file.
Note: You must open the file only once in "r+" mode.

Source code: -
def Sale():
print("=== Product Sale Records ===")

# Open file in r+ mode

f = open("Product.txt", "r+")

# Step 1: Read existing records

f.seek(0)
lines = f.readlines()

print("\n--- Existing Records ---")


print("{:<10}{:<10}{:<10}{:<10}".format("Code", "Qty", "Price", "Total"))
for line in lines:
data = line.strip().split()
if len(data) == 4: # Ensure valid record
print("{:<10}{:<10}{:<10}{:<10}".format(data[0], data[1], data[2],
data[3]))

# Step 2: Add new records

n = int(input("\nEnter number of new records to add: "))


for i in range(n):
print(f"\n--- Enter record {i + 1} ---")
code = input("Enter Product Code: ")
qty = int(input("Enter Quantity: "))
price = float(input("Enter Price: "))
total = qty * price
record = f"{code} {qty} {price} {total}\n"
f.write(record)

# Step 3: Display updated file

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

=== Product Sale Records ===

--- Existing Records ---


Code Qty Price Total
P001 5 100 500
P002 3 200 600

Enter number of new records to add: 2

--- Enter record 1 ---


Enter Product Code: P003
Enter Quantity: 4
Enter Price: 150

--- Enter record 2 ---


Enter Product Code: P004
Enter Quantity: 2
Enter Price: 250

--- Updated Records in Product.txt ---


Code Qty Price Total
P001 5 100 500
P002 3 200 600
P003 4 150.0 600.0
P004 2 250.0 500.0

=== Process Completed ===

Conclusion: - The program was executed successfully.

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

# Step 1: Open file in a+ mode


f = open("IPL_Champ.txt", "a+")

# Step 2: Add new records


n = int(input("Enter number of new records to add: "))
for i in range(n):
print(f"\n--- Enter record {i+1} ---")
team = input("Enter Team Name: ")
year = input("Enter Champion Year: ")
record = f"{team} {year}\n"
f.write(record)

# Step 3: Read all records (reset pointer to start)


f.seek(0)
print("\n--- All IPL Champion Records ---")
print("{:<5}{:<25}{:<10}".format("No.", "Team", "Year"))
print("-" * 45)
count = 1
for line in f:
data = line.strip().split()
if len(data) >= 2:
team = " ".join(data[:-1]) # Handles team names with spaces
year = data[-1]
print("{:<5}{:<25}{:<10}".format(count, team, year))
count += 1
f.close()
print("\n=== Process Completed ===")
Output of the code: -
=== IPL Champion Records ===
Enter number of new records to add: 2

--- Enter record 1 ---


Enter Team Name: Gujarat Titans
Enter Champion Year: 2022

--- Enter record 2 ---


Enter Team Name: Kolkata Knight Riders
Enter Champion Year: 2014

--- All IPL Champion Records ---


No. Team Year
----------------------------------------
1 Mumbai Indians 2019
2 Chennai SuperKings 2021
3 Gujarat Titans 2022
4 Kolkata Knight Riders 2014

=== Process Completed ===

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

Output of the code: -


Enter an integer number: 77
Do you want to add more numbers? (y/n): y
Enter an integer number: 42
Do you want to add more numbers? (y/n): y
Enter an integer number: 27
Do you want to add more numbers? (y/n): y
Enter an integer number: 55
Do you want to add more numbers? (y/n): y
Enter an integer number: 127
Do you want to add more numbers? (y/n): n

Numbers successfully stored in Number.dat!

Numbers retrieved from Number.dat are:


1. 77
2. 42
3. 27
4. 55
5. 127

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

with open("Number.dat", "rb") as f:

numbers = pickle.load(f) # Load the list of numbers

print("Numbers divisible by 7 or ending with 7 are:\n")

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

# Call the function

Display()

Output of the code: -


Numbers divisible by 7 or ending with 7 are:

77
42
27
127

Conclusion: - The program was executed successfully.

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

Output of the code: -


Name Class Rank
-----------------------------------
Rohan XII-A 1
Aman XII-C 1

Conclusion: - The program was executed successfully.

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

print("{:<10} {:<20} {:<20}".format("Number", "Binary", "Octal"))


print("-" * 50)

for num in numbers:


print("{:<10} {:<20} {:<20}".format(num, bin(num), oct(num)))

# Example call

Conversion()

Output of the code: -


Enter an integer: 7
Number Binary Octal
--------------------------------------------------
77 0b1001101 0o115
42 0b101010 0o52
27 0b11011 0o33
55 0b110111 0o67
127 0b1111111 0o177

Conclusion: - The program was executed successfully.

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

print("{:<15} {:<15} {:<15}".format("Name", "Uppercase", "Lowercase"))


print("-" * 45)

for name in names:


upper = sum(1 for ch in name if ch.isupper())
lower = sum(1 for ch in name if ch.islower())
print("{:<15} {:<15} {:<15}".format(name, upper, lower))

# Example call
Count()

Output of the code: -


Name Uppercase Lowercase
---------------------------------------------
Ujjwal 1 5
SANJAY 6 0
yadav 0 5

Conclusion: - The program was executed successfully.

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

vowels = ('A', 'E', 'I', 'O', 'U')

print("{:<20} {:<20}".format("State", "Capital"))


print("-" * 40)

for state, capital in states:


if not state[0].upper().startswith(vowels): # check if first letter is NOT
vowel
print("{:<20} {:<20}".format(state, capital))

# Example call
State_Cap()

Output of the code: -


State Capital
----------------------------------------
Maharashtra Mumbai
Rajasthan Jaipur

Conclusion: - The program was executed successfully.

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

print("Students with 90% and above in all subjects:")


print("-" * 40)

for record in data:


name, eng, maths, cs = record
if eng >= 90 and maths >= 90 and cs >= 90:
print(name)

# Example call
Result()

Output of the code: -


Students with 90% and above in all subjects:
----------------------------------------
Aarav
Rohit
Ishita

Conclusion: - The program was executed successfully.

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

n = int(input("Enter number of new books to add: "))


for i in range(n):
index = int(input("Enter Book Index Number: "))
name = input("Enter Book Name: ")
record = (index, name)
pickle.dump(record, f) # save each record
print("Book added successfully!\n")

f.close()

Output of the code: -


Enter number of new books to add: 2
Enter Book Index Number: 101
Enter Book Name: Physics NCERT
Book added successfully!

Enter Book Index Number: 102


Enter Book Name: Computer Science
Book added successfully!

Conclusion: - The program was executed successfully.

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

Output of the code: -


Enter the name to search: Ujjwal
The record is found
Name : Ujjwal
Phone: 9988776655

Enter the name to search: Rahul


No such name is available in the file.

Enter the name to search: Sneha


The record is found
Name : Sneha
Phone: 8899776655

Conclusion: - The program was executed successfully.

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

# Open CSV file in write mode

with open("Holiday.csv", "w", newline="") as f:

writer = csv.writer(f)

# Write header

writer.writerow(["Type", "Trip", "Days", "Tour Cost"])

# Ask user how many records they want to enter

n = int(input("Enter number of holiday packages: "))

for i in range(n):

print(f"\nEnter details for package {i+1}:")

type_code = input("Type (e.g., A01): ")

trip = input("Trip (e.g., Delhi-Agra): ")

days = int(input("Days: "))

cost = int(input("Tour Cost: "))

# Write one record into CSV

writer.writerow([type_code, trip, days, cost])

58
Output of the code: -
Enter number of holiday packages: 8

Enter details for package 1:


Type: A01
Trip: Delhi-Agra
Days: 2
Tour Cost: 5000

Enter details for package 2:


Type: A02
Trip: Delhi-Goa
Days: 3
Tour Cost: 8000

Enter details for package 3:


Type: A03
Trip: Delhi-Manali
Days: 4
Tour Cost: 10000

Enter details for package 4:


Type: A04
Trip: Delhi-Shimla
Days: 5
Tour Cost: 12000

Enter details for package 5:


Type: A05
Trip: Delhi-Kerala
Days: 6
Tour Cost: 15000

Enter details for package 6:


Type: A06
Trip: Delhi-Jaipur
Days: 3
Tour Cost: 7000

Enter details for package 7:


Type: A07
Trip: Delhi-Udaipur
Days: 4
Tour Cost: 11000

Enter details for package 8:


Type: A08
Trip: Delhi-Kashmir
Days: 7
Tour Cost: 20000

Conclusion: - The program was executed successfully.

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)

for row in reader:


print(f"{row[0]:<8}{row[1]:<20}{row[2]:<10}{row[3]:<10}")

Output of the code: -


Type Trip Days Tour Cost
--------------------------------------------------
A01 Delhi-Agra 2 5000
A02 Delhi-Goa 3 8000
A03 Delhi-Manali 4 10000
A04 Delhi-Shimla 5 12000
A05 Delhi-Kerala 6 15000
A06 Delhi-Jaipur 3 7000
A07 Delhi-Udaipur 4 11000
A08 Delhi-Kashmir 7 20000

Conclusion: - The program was executed successfully.

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

with open("Employee.csv", "r") as f:


reader = csv.reader(f)
header = next(reader) # Read header row
print(f"{header[0]:<10}{header[1]:<20}{header[2]:<10}{header[3]:<10}")
print("-"*55)

for row in reader:

if int(row[3]) >= 40000:


print(f"{row[0]:<10}{row[1]:<20}{row[2]:<10}{row[3]:<10}")

Output of the code: -


Emp_Code Name Grade Salary
-------------------------------------------------------
E/01 Anand Mishra SP4 45000
E/02 Ramesh Shukla SP3 41000

Conclusion: - The program was executed successfully.

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

Output of the code: -


Code Item Company Price Quantity
--------------------------------------------------
T/01 Television LG 42000 15
T/02 Television Sony 45000 20
T/03 Television Samsung 40000 10

Conclusion: - The program was executed successfully.

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)

# Find record with minimum fee


min_record = min(records, key=lambda x: int(x['Fee']))

print("Record with minimum fee:")


for key, value in min_record.items():
print(f"{key}: {value}")

# Call function
MinFee()

Output of the code: -


Record with minimum fee:
Code: L/01
Course Name: LLB
Qualification: Intermediate
Fee: 700000
Duration: 3 Years

Conclusion: - The program was executed successfully.

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

for row in reader:


if row["School Name"].lower() == school_name.lower():
total = int(row["Gold"]) + int(row["Silver"]) + int(row["Bronze"])
print(f"Total medals won by {row['School Name']}: {total}")
found = True
break

if not found:
print("School not found in the records.")

# Call the function


Medals()

Output of the code: -


Enter School Name: Hill View
Total medals won by Hill View: 15

Enter School Name: XYZ Public


School not found in the records.

Conclusion: - The program was executed successfully.


64
7) Aim: The file 'Quiz.csv' keeps the records of two participants per school for the event.
Later on, few more schools had participated in this event. Write a function def Participate()
to add the details and update the file for those who participated late. The different fields are
as shown below:
School Name Name 1 Class Name 2 Class
………………. …………. ……… ………….. ………
………………. …………. ……… ………….. ………
[Assume that the file is already present in the hard disk.]
Source code: -
import csv

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)

# ask how many schools want to add


n = int(input("Enter number of new schools to add: "))

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

# write new row


writer.writerow([school, name1, class1, name2, class2])

print("\nRecords updated successfully in Quiz.csv")


Output of the code: -
Enter number of new schools to add: 2

Enter details for School 1:


School Name: Green Bird
Name 1: Raj
Class of Name 1: 10
Name 2: Meera
Class of Name 2: 9

Enter details for School 2:


School Name: Sun Shine
Name 1: Karan
Class of Name 1: 11
Name 2: Neha
Class of Name 2: 12

Records updated successfully in Quiz.csv

Conclusion: - The program was executed successfully.


65
PYTHON LIBRARIES

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)

octal_num = 0o31 # Octal (base 8) -> decimal 25

hex_num = 0x19 # Hexadecimal (base 16) -> decimal 25

# Convert all into binary using bin()


print("Decimal to Binary:", bin(decimal_num))

print("Octal to Binary :", bin(octal_num))

print("Hex to Binary :", bin(hex_num))

Output of the code: -

Decimal to Binary: 0b11001


Octal to Binary : 0b11001
Hex to Binary : 0b11001

Conclusion: - The program was executed successfully.

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

octal_num = 0o25 # Octal (base 8) -> decimal 21

hex_num = 0x15 # Hexadecimal (base 16) -> decimal 21

# Convert all into decimal


print("Binary to Decimal :", int(binary_num))

print("Octal to Decimal :", int(octal_num))

print("Hexadecimal to Decimal:", int(hex_num))

Output of the code: -

Binary to Decimal : 21
Octal to Decimal : 21
Hexadecimal to Decimal: 21

Conclusion: - The program was executed successfully.

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)

binary_num = 0b1100100 # Binary (base 2) -> decimal 100

hex_num = 0x64 # Hexadecimal (base 16) -> decimal 100

# Convert to octal using oct()


print("Decimal to Octal :", oct(decimal_num))

print("Binary to Octal :", oct(binary_num))

print("Hexadecimal to Octal :", oct(hex_num))

Output of the code: -


Decimal to Octal : 0o144
Binary to Octal : 0o144
Hexadecimal to Octal : 0o144

Conclusion: - The program was executed successfully.

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

# simulate 20 tosses (H for Head, T for Tail)


tosses = [random.choice(['H', 'T']) for _ in range(20)]

# count heads and tails


heads = tosses.count('H')
tails = tosses.count('T')

print("Toss Results :", tosses)


print("Total Heads :", heads)
print("Total Tails :", tails)

Output of the code: -


Toss Results : ['H', 'H', 'T', 'T', 'H', 'T', 'H', 'H', 'T', 'T', 'T', 'T', 'T', 'T',
'H', 'T', 'H', 'T', 'H', 'T']
Total Heads : 8
Total Tails : 12

Conclusion: - The program was executed successfully.

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)

mysql> USE School;


Database changed
mysql> CREATE TABLE Student (
-> RollNo INT PRIMARY KEY,
-> Name VARCHAR(50),
-> Class INT,
-> Marks INT
-> );
Query OK, 0 rows affected (0.10 sec)

mysql> INSERT INTO Student (RollNo, Name, Class, Marks) VALUES


-> (1, 'Amit', 10, 450),
-> (2, 'Riya', 10, 480),
-> (3, 'Sam', 12, 420),
-> (4, 'Neha', 11, 460),
-> (5, 'Karan', 12, 470),
-> (6, 'Sneha', 10, 490);
Query OK, 6 rows affected (0.02 sec)
Records: 6 Duplicates: 0 Warnings: 0

Output of the code: -


+--------+-------+-------+-------+
| RollNo | Name | Class | Marks |
+--------+-------+-------+-------+
| 1 | Amit | 10 | 450 |
| 2 | Riya | 10 | 480 |
| 3 | Sam | 12 | 420 |
| 4 | Neha | 11 | 460 |
| 5 | Karan | 12 | 470 |
| 6 | Sneha | 10 | 490 |
+--------+-------+-------+-------+
6 rows in set (0.01 sec)

Conclusion: - The program was executed successfully.

70
2) Aim: Write SQL commands to retrieve data using the SELECT clause.

Source code: -
-- Show all records
SELECT * FROM health_drink;

-- Show only Name and Price


SELECT Name, price FROM health_drink;

-- Show all drinks with price > 400


SELECT * FROM health_drink WHERE price > 400;

Output of the code: -


Show all records
+----+-----------+-------+------+------+-------+---------+---------+
| 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 |
+----+-----------+-------+------+------+-------+---------+---------+
Show only Name and Price
+-----------+-------+
| Name | price |
+-----------+-------+
| Bournvita | 80 |
| Bournvita | 80 |
| Horlicks | 320 |
| Horlicks | 350 |
| Ensure | 450 |
| Ensure | 500 |
| Complan | 400 |
| Complan | 420 |
| Complan | 380 |
+-----------+-------+
Show all drinks with price > 400
+----+---------+-------+------+------+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+---------+-------+------+------+-------+---------+---------+
| 5 | Ensure | Plain | E1 | 100 | 450 | 210 | 650 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
+----+---------+-------+------+------+-------+---------+---------+

Conclusion: - The program was executed successfully.

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;

-- Order records by Calcium in descending order


SELECT * FROM health_drink ORDER BY Calcium DESC;

-- Order records by Name alphabetically, then Price in descending order


SELECT * FROM health_drink ORDER BY Name ASC, Price DESC;

Output of the code: -

Order records by Price in ascending order


+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 1 | Bournvita | Plain | B1 | 100 | 80 | 130 | 440 |
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 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 |
+----+-----------+-------+------+-----+-------+---------+---------+

Order records by Calcium in descending order


+----+--------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+--------+-------+------+-----+-------+---------+---------+
| 5 | Ensure | Plain | E1 | 100 | 450 | 210 | 650 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 3 | Horlicks|Plain | H1 | 100 | 320 | 150 | 450 |
| 4 | Horlicks|Choco | H1 | 120 | 350 | 180 | 450 |
| 1 | Bournvita|Plain| B1 | 100 | 80 | 130 | 440 |
| 2 | Bournvita|Choco| B1 | 160 | 80 | 200 | 440 |
| 7 | Complan | Plain| C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco| C1 | 150 | 420 | 160 | 350 |
| 9 | Complan | Plain| C1 | 170 | 380 | 140 | 350 |
+----+--------+-------+------+-----+-------+---------+---------+

Order records by Name alphabetically, then Price in descending order


+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
| 1 | Bournvita | Plain | B1 | 100 | 80 | 130 | 440 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 5 | Ensure | Plain | E1 | 100 | 450 | 210 | 650 |
| 4 | Horlicks | Choco | H1 | 120 | 350 | 180 | 450 |
| 3 | Horlicks | Plain | H1 | 100 | 320 | 150 | 450 |
+----+-----------+-------+------+-----+-------+---------+---------+

Conclusion: - The program was executed successfully.


72
4) Aim: Write SQL queries to retrieve data from the table using the GROUP BY clause with
the COUNT() function.
Source code: -
-- Count of products by brand name
SELECT Name, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Name;

-- Count of products by title (Plain/Choco)


SELECT Title, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Title;

-- Count of products by code


SELECT Code, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Code;

Output of the code: -

Count of products by brand name


+-----------+----------------+
| Name | Total_Products |
+-----------+----------------+
| Bournvita | 2 |
| Horlicks | 2 |
| Ensure | 2 |
| Complan | 3 |
+-----------+----------------+

Count of products by title (Plain/Choco)


+-------+----------------+
| Title | Total_Products |
+-------+----------------+
| Plain | 5 |
| Choco | 4 |
+-------+----------------+

Count of products by code


+------+----------------+
| Code | Total_Products |
+------+----------------+
| B1 | 2 |
| H1 | 2 |
| E1 | 2 |
| C1 | 3 |
+------+----------------+

Conclusion: - The program was executed successfully.

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;

-- Titles having at least 3 products


SELECT Title, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Title
HAVING COUNT(*) >= 3;

-- Codes having more than 2 products


SELECT Code, COUNT(*) AS Total_Products
FROM health_drink
GROUP BY Code
HAVING COUNT(*) > 2;

Output of the code: -

Brands having more than 2 products


+---------+----------------+
| Name | Total_Products |
+---------+----------------+
| Complan | 3 |
+---------+----------------+

Titles having at least 3 products


+-------+----------------+
| Title | Total_Products |
+-------+----------------+
| Plain | 5 |
+-------+----------------+

Codes having more than 2 products


+------+----------------+
| Code | Total_Products |
+------+----------------+
| C1 | 3 |
+------+----------------+

Conclusion: - The program was executed successfully.

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%';

-- Title ends with 'o'


SELECT * FROM health_drink
WHERE Title LIKE '%o';

-- Name contains 'm'


SELECT * FROM health_drink
WHERE Name LIKE '%m%';

-- Code starts with 'C'


SELECT * FROM health_drink
WHERE Code LIKE 'C%';

Output of the code: -

Name starts with 'B'


+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 1 | Bournvita | Plain | B1 | 100 | 80 | 130 | 440 |
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
+----+-----------+-------+------+-----+-------+---------+---------+

Title ends with 'o'


+----+-----------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+-----------+-------+------+-----+-------+---------+---------+
| 2 | Bournvita | Choco | B1 | 160 | 80 | 200 | 440 |
| 4 | Horlicks | Choco | H1 | 120 | 350 | 180 | 450 |
| 6 | Ensure | Choco | E1 | 140 | 500 | 230 | 650 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
+----+-----------+-------+------+-----+-------+---------+---------+

Name contains 'm'


+----+---------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+---------+-------+------+-----+-------+---------+---------+
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
+----+---------+-------+------+-----+-------+---------+---------+

Code starts with 'C'


+----+---------+-------+------+-----+-------+---------+---------+
| No | Name | Title | Code | Qty | Price | Vitamin | Calcium |
+----+---------+-------+------+-----+-------+---------+---------+
| 7 | Complan | Plain | C1 | 100 | 400 | 140 | 350 |
| 8 | Complan | Choco | C1 | 150 | 420 | 160 | 350 |
| 9 | Complan | Plain | C1 | 170 | 380 | 140 | 350 |
+----+---------+-------+------+-----+-------+---------+---------+

Conclusion: - The program was executed successfully.


75
7) Aim: Write SQL queries to retrieve data from the table using the WHERE clause with
different conditions.
Source code: -
-- Students who scored more than 470 marks
SELECT Name, Marks
FROM Student
WHERE Marks > 470;

-- Students whose name ends with 'a'


SELECT Name, Marks
FROM Student
WHERE Name LIKE '%a';

-- Students whose marks are between 450 and 480


SELECT Name, Marks
FROM Student
WHERE Marks BETWEEN 450 AND 480;

-- Students not in Class 10


SELECT Name, Class, Marks
FROM Student
WHERE Class <> 10;

Output of the code: -


-- Students who scored more than 470 marks
+-------+-------+
| Name | Marks |
+-------+-------+
| Riya | 480 |
| Sneha | 490 |
+-------+-------+

-- Students whose name ends with 'a'


+-------+-------+
| Name | Marks |
+-------+-------+
| Riya | 480 |
| Sneha | 490 |
+-------+-------+

-- Students whose marks are between 450 and 480


+-------+-------+
| Name | Marks |
+-------+-------+
| Amit | 450 |
| Riya | 480 |
+-------+-------+

-- Students not in Class 10


+-------+-------+-------+
| Name | Class | Marks |
+-------+-------+-------+
| Sneha | 11 | 490 |
+-------+-------+-------+

Conclusion: - The program was executed successfully.


76
8) Aim: Write SQL queries to retrieve data from two tables using the WHERE and AND
operators.
Source code: -
-- Students who scored more than 470 marks
SELECT Name, Marks
FROM Student
WHERE Marks > 470;

-- Students whose name ends with 'a'


SELECT Name, Marks
FROM Student
WHERE Name LIKE '%a';

-- Students whose marks are between 450 and 480


SELECT Name, Marks
FROM Student
WHERE Marks BETWEEN 450 AND 480;

-- Students not in Class 10


SELECT Name, Class, Marks
FROM Student
WHERE Class <> 10;

Output of the code: -

-- Students who scored more than 470 marks


+-------+-------+
| Name | Marks |
+-------+-------+
| Riya | 480 |
| Sneha | 490 |
+-------+-------+

-- Students whose name ends with 'a'


+-------+-------+
| Name | Marks |
+-------+-------+
| Riya | 480 |
| Sneha | 490 |
+-------+-------+

-- Students whose marks are between 450 and 480


+------+-------+
| Name | Marks |
+------+-------+
| Amit | 450 |
| Riya | 480 |
+------+-------+

-- Students not in Class 10


+-------+-------+-------+
| Name | Class | Marks |
+-------+-------+-------+
| Sneha | 11 | 490 |
+-------+-------+-------+

Conclusion: - The program was executed successfully.


77
INTERFACE OF PYTHON WITH
(MYSQL)
1) Aim: Write a Python program to connect with MySQL and create a table.
Source code: -
import mysql.connector as mycon

# establish connection
mydb = mycon.connect(
host="localhost",
user="root",
passwd="1147", # your password
database="ujjwal" # make sure database exists
)

cur = mydb.cursor()

# create table query


cur.execute("""
CREATE TABLE health_drink (
No INT PRIMARY KEY,
Name VARCHAR(30),
Title VARCHAR(20),
Code VARCHAR(10),
Qty INT,
Price INT,
Vitamin INT,
Calcium INT
)
""")

print("Table 'health_drink' created successfully.")

Output of the code: -

Table 'health_drink' created successfully.

Conclusion: - The program was executed successfully.

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

print(cursor.rowcount, "records inserted successfully into ujjwal.health_drink.")

# 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 |
+----+-----------+-------+------+-----+-------+---------+---------+

Conclusion: - The program was executed successfully.


79
3) Aim: To write a Python program to interface with MySQL and retrieve data from the table
using the fetchall() method.

Source code: -
import mysql.connector

# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="1147",
database="ujjwal"
)

cursor = conn.cursor()

# Execute query to fetch all records


cursor.execute("SELECT * FROM health_drink")

# Fetch all records


rows = cursor.fetchall()

print("Data from health_drink table:")


for row in rows:
print(row)

# Close connection
cursor.close()
conn.close()

Output of the code: -

Data from health_drink table:


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

Conclusion: - The program was executed successfully.

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

# Update query: Increase price of 'Bournvita' Plain by 10


cur.execute("""
UPDATE health_drink
SET price = price + 10
WHERE Name = 'Bournvita' AND Title = 'Plain'
""")

mydb.commit()

print("Record updated successfully!")

# Fetch updated records


cur.execute("SELECT * FROM health_drink WHERE Name='Bournvita'")
for row in cur.fetchall():
print(row)

Output of the code: -

+----+-----------+-------+------+-----+-------+---------+---------+
| 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 |
+----+-----------+-------+------+-----+-------+---------+---------+

Conclusion: - The program was executed successfully.

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

# Delete query: delete Complan Plain


cur.execute("""
DELETE FROM health_drink
WHERE Name = 'Complan' AND Title = 'Plain'
""")

mydb.commit()

print(cur.rowcount, "record(s) deleted successfully!")

# Fetch updated records


cur.execute("SELECT * FROM health_drink")
for row in cur.fetchall():
print(row)

Output of the code: -

1 record(s) deleted successfully!


(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)
(8, 'Complan', 'Choco', 'C1', 150, 420, 160, 350)

Conclusion: - The program was executed successfully.

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

# Step 1: Create a new table (if not exists)

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

# Step 2: Insert record using parameterized query with user input

insert_query = "INSERT INTO sports (PlayerName, Game, Score) VALUES (%s, %s, %s)"

n = int(input("Enter number of records you want to insert: "))

for i in range(n):
print(f"\nRecord {i+1}:")
name = input("Enter Player Name: ")
game = input("Enter Game: ")
score = int(input("Enter Score: "))

cur.execute(insert_query, (name, game, score))

# Commit changes

mydb.commit()

print(f"\n{n} record(s) inserted successfully!")

# Step 3: Fetch and display records

cur.execute("SELECT * FROM sports")


print("\n--- Sports Table Data ---")
for row in cur.fetchall():
print(row)

# 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

4 record(s) inserted successfully!

--- Sports Table Data ---


(1, 'Amit', 'Cricket', 80)
(2, 'Riya', 'Football', 65)
(3, 'Sneha', 'Tennis', 40)
(4, 'Mohit', 'Badminton', 55)

In MySQL:
+----+------------+-----------+-------+
| ID | PlayerName | Game | Score |
+----+------------+-----------+-------+
| 1 | Amit | Cricket | 80 |
| 2 | Riya | Football | 65 |
| 3 | Sneha | Tennis | 40 |
| 4 | Mohit | Badminton | 55 |
+----+------------+-----------+-------+

Conclusion: - The program was executed successfully.

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

# Parameterized query with WHERE clause


select_query = "SELECT * FROM sports WHERE Game = %s"

# Take user input for game


game = input("Enter game to search: ")

cur.execute(select_query, (game,))

# Fetch and display results


records = cur.fetchall()
if records:
print("\n--- Players Found ---")
for row in records:
print(row)
else:
print("No records found!")

# Close connection
cur.close()
mydb.close()

Output of the code: -


Enter game to search: Cricket

--- Players Found ---


(1, 'Amit', 'Cricket', 80)

Enter game to search: Football

--- Players Found ---


(2, 'Riya', 'Football', 65)

Enter game to search: Hockey


No records found!

Conclusion: - The program was executed successfully.

85

You might also like