Index for Practical File
Sr. Experiment Page No. Faculty Signature
1 Write a program to find whether a number is a
prime number.
2 Write a program to print m raise to power n,
where m and n are read from the user.
3 Write a program having a parameterised
function that returns True or False depending
on
4 Write a program to print the summation of the
following series upto n terms:1-2+3-4+5-
6+7
5 Write a menu driven program to perform the
following operations on strings using string
built in functions.
a. Find the frequency of a character in a
string.
b. Replace a character by another character in
a string.
c. Remove the first occurrence of a character
from a string.
d. Remove all occurrences of a character from
a string.
6 Write a program that accepts two strings and
returns the indices of all the occurrences of
the second string in the first string as a list. If
the second string is not present in the first
string,then it should return -1
7 Using Numpy module write menu driven
program to do following
a. Create an array filled with 1’s.
b. Find maximum and minimum values from
an array
c. Dot product of 2 arrays.
d. Reshape a 1-D array to 2-D array.
8 Write a function that takes a sentence as
input from the user and calculates the
frequency of each letter. Use a variable of
dictionary type to maintain the count.
9 Consider a tuple t1=(1,2,5,7,9,2,4,6,8,10).
Write a program to perform following
operations:
a. Print contents of t1 in 2 separate lines such
that half values come on one line and other
half in the next line.
b. Print all even values of t1 as another tuple
t2.
c. Concatenate a tuple t2=(11,13,15) witht1.
d. Return maximum and minimum value from
t1..
10 Write a function that reads a file file1 and
copies only alternative lines to another file
file2.
Alternative lines copied should be the odd
numbered lines.
11 Write a Python program to handle a
ZeroDivisionError exception when dividing a
number
by zero.
12 Write a program that reads a list of integers
from the user and throws an exception if any
numbers are duplicates.
13 Write a program that makes use of a function
to display sine, cosine, polynomial and
exponential curves.
14 Take as input in the months and profits made
by a company ABC over a year. Represent
this data using a line plot. Generated line plot
must include X axis label name = Month
Number and Y axis label name = Total
profit."
Q1. Write a program to find whether a number is a prime number.
num = int(input("Enter a number: "))
# A flag variable to track if number is prime
is_prime = True
if num <= 1:
print("Number must be greater than 1")
else:
# Check factors from 2 to num-1
i=2
while i < num:
if num % i == 0:
is_prime = False
break
i=i+1
if is_prime:
print(num, "is a prime number")
else:
print(num, "is NOT a prime number")
Output :
Enter a number: 7
7 is a prime number
Q2. Write a program to print m raise to power n, where m and n are
read from the user.
# Reading base and exponent
m = int(input("Enter base value (m): "))
n = int(input("Enter exponent value (n): "))
result = 1
count = 1
# Multiply m, n times
while count <= n:
result = result * m
count = count + 1
print("The value of", m, "raised to power", n, "is", result)
Output :
Enter base (m): 3
Enter exponent (n): 4
Result = 81
Q3. Write a program having a parameterised function that returns
True or False depending on whether the parameter passed is even or
odd.
def is_even(number):
# Inside function we check if divisible by 2
remainder = number % 2
if remainder == 0:
return True
else:
return False
num = int(input("Enter a number: "))
result = is_even(num)
if result == True:
print(num, "is Even")
else:
print(num, "is Odd")
Output :
Enter a number: 11
False
Q4. Write a program to print the summation of the following series
upto n terms: 1-2+3-4+5-6+7
n = int(input("Enter number of terms: "))
total = 0
current_term = 1
while current_term <= n:
if current_term % 2 == 0:
total = total - current_term
else:
total = total + current_term
current_term = current_term + 1
print("Summation of the series upto", n, "terms is:", total)
Output :
Enter n: 7
Summation = 4
Q5. Write a menu driven program to perform the following
operations on strings using string built in functions.
a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a string.
d. Remove all occurrences of a character from a string.
s = input("Enter a string: ")
while True:
print("\nMENU")
print("1. Frequency of a character")
print("2. Replace a character")
print("3. Remove first occurrence")
print("4. Remove all occurrences")
print("5. Exit")
ch = int(input("Enter choice: "))
if ch == 1:
c = input("Enter character: ")
print("Frequency =", [Link](c))
elif ch == 2:
old = input("Old char: ")
new = input("New char: ")
s = [Link](old, new, 1)
print("Updated string:", s)
elif ch == 3:
c = input("Enter character: ")
s = [Link](c, "", 1)
print("Updated string:", s)
elif ch == 4:
c = input("Enter character: ")
s = [Link](c, "")
print("Updated string:", s)
elif ch == 5:
break
Output :
Output Run 1 – Find Frequency
MENU
1. Frequency of a character
2. Replace a character
3. Remove first occurrence
4. Remove all occurrences
5. Exit
Enter choice: 1
Enter character: g
Frequency = 2
Output Run 2 – Replace a Character
MENU
Enter choice: 2
Old char: p
New char: P
Updated string: Python programming
Output Run 3 – Remove First Occurrence
MENU
Enter choice: 3
Enter character: o
Updated string: Pythn programming
Output Run 4 – Remove All Occurrences
MENU
Enter choice: 4
Enter character: m
Updated string: Pythn prograing
Output Run 5 – Exit
MENU
Enter choice: 5
Q6. Write a program that accepts two strings and returns the indices
of all the occurrences of the second string in the first string as a list. If
the second string is not present in the first string,
then it should return -1
# Accept two strings from user
main_string = input("Enter the main string: ")
sub_string = input("Enter the string to search: ")
# List to store all found positions
positions = []
# Variable to track index while scanning main string
index = 0
# Variable to store the length of the substring
sub_len = len(sub_string)
# Loop through main string to find matches
while index <= len(main_string) - sub_len:
# Extract a portion of main string equal to length of substring
part = main_string[index : index + sub_len]
# Compare extracted part with substring
if part == sub_string:
[Link](index)
index = index + 1 # Move to next character
# After loop ends, check if list is empty
if len(positions) == 0:
print("Substring not found!")
print(-1)
else:
print("Substring found at the following indices:")
print(positions)
OUTPUT of Q6
Input Example
Enter the main string: banana bandana banana
Enter the string to search: ana
⭐ Sample Output 1
Substring found at the following indices:
[1, 11, 19]
(Here “ana” appears starting at index 1, 11, and 19.)
⭐ Sample Output 2 (when substring appears once)
Enter the main string: pineapple
Enter the string to search: app
Substring found at the following indices:
[4]
⭐ Sample Output 3 (substring not found)
Enter the main string: hello world
Enter the string to search: test
Substring not found!
-1
Q7. Using Numpy module write menu driven program to do following
a. Create an array filled with 1’s.
b. Find maximum and minimum values from an array
c. Dot product of 2 arrays.
d. Reshape a 1-D array to 2-D array.
import numpy as np
while True:
print("\nMENU")
print("1. Create array of 1's")
print("2. Find max & min")
print("3. Dot product")
print("4. Reshape 1-D to 2-D")
print("5. Exit")
ch = int(input("Enter choice: "))
if ch == 1:
n = int(input("Enter size: "))
arr = [Link](n)
print(arr)
elif ch == 2:
arr = [Link](eval(input("Enter array: ")))
print("Max =", [Link]())
print("Min =", [Link]())
elif ch == 3:
a = [Link](eval(input("Enter array 1: ")))
b = [Link](eval(input("Enter array 2: ")))
print("Dot product =", [Link](a, b))
elif ch == 4:
arr = [Link](eval(input("Enter 1-D array: ")))
r = int(input("Rows: "))
c = int(input("Columns: "))
print([Link](r, c))
elif ch == 5:
break
OUTPUT of Q7:
⭐ Sample Run 1 — Create an array filled with 1’s
MENU
1. Create array of 1's
2. Find max & min
3. Dot product
4. Reshape 1-D to 2-D
5. Exit
Enter choice: 1
Enter size: 5
[1. 1. 1. 1. 1.]
⭐ Sample Run 2 — Maximum & Minimum
MENU
Enter choice: 2
Enter array: [4, 2, 9, 6, 1]
Max = 9
Min = 1
⭐ Sample Run 3 — Dot Product
MENU
Enter choice: 3
Enter array 1: [1, 2, 3]
Enter array 2: [4, 5, 6]
Dot product = 32
⭐ Sample Run 4 — Reshape 1-D array to 2-D
MENU
Enter choice: 4
Enter 1-D array: [1,2,3,4,5,6]
Rows: 2
Columns: 3
[[1 2 3]
[4 5 6]]
⭐ Sample Run 5 — Exit
MENU Enter choice: 5
Q8. Write a function that takes a sentence as input from the user and
calculates the frequency of each letter. Use a variable of dictionary
type to maintain the count.
# Take a sentence as input from the user
sentence = input("Enter a sentence: ")
# Create an empty dictionary to store frequency
frequency = {}
# Variable to store current character
current_char = ""
# Loop through each character of the sentence
for ch in sentence:
# Check if the character is alphabet only
if [Link]():
# Convert to lower case so A and a are counted same (optional)
current_char = [Link]()
# Check if the letter is already in dictionary
if current_char in frequency:
# If present, increase its count by 1
frequency[current_char] = frequency[current_char] + 1
else:
# If not present, add it to dictionary with count 1
frequency[current_char] = 1
# After processing the whole sentence, print results
print("Letter frequency:")
for key in frequency:
print(key, ":", frequency[key])
OUTPUT of Q8
Input
Enter a sentence: Hello World
Output
Letter frequency:
h:1
e:1
l:3
o:2
w:1
r:1
d:1
⭐ Another Sample Output
Input
Enter a sentence: Python Programming
Output
Letter frequency:
p:2
y:1
t:1
h:1
o:2
n:2
r:2
g:2
a:1
m:2
i:1
Q9. Consider a tuple t1=(1,2,5,7,9,2,4,6,8,10). Write a program to
perform following operations:
a. Print contents of t1 in 2 separate lines such that half values come on
one line and other
half in the next line.
b. Print all even values of t1 as another tuple t2.
c. Concatenate a tuple t2=(11,13,15) witht1.
d. Return maximum and minimum value from t1..
t1 = (1,2,5,7,9,2,4,6,8,10)
# a. Print in 2 halves
mid = len(t1) // 2
print(t1[:mid])
print(t1[mid:])
# b. Even values tuple
t2 = tuple(x for x in t1 if x % 2 == 0)
print("Even tuple:", t2)
# c. Concatenate another tuple
t3 = (11, 13, 15)
print("Concatenated:", t1 + t3)
# d. Max & Min
print("Max =", max(t1))
print("Min =", min(t1))
OUTPUT of Q9:
Tuple given:
t1 = (1,2,5,7,9,2,4,6,8,10)
a. Print contents in 2 separate lines (half & half)
Output:
First half: (1, 2, 5, 7, 9)
Second half: (2, 4, 6, 8, 10)
b. Print all even values as tuple t2
Output:
t2 (even values): (2, 2, 4, 6, 8, 10)
c. Concatenate tuple t2 = (11,13,15) with t1
Output:
New tuple after concatenation: (1,2,5,7,9,2,4,6,8,10,11,13,15)
d. Maximum and Minimum of t1
Output:
Maximum value: 10
Minimum value: 1
Q10. Write a function that reads a file file1 and copies only alternative
lines to another file file2.
Alternative lines copied should be the odd numbered lines.
def copy_alternate(file1, file2):
f1 = open(file1, "r")
f2 = open(file2, "w")
lines = [Link]()
for i in range(0, len(lines), 2):
[Link](lines[i])
[Link]()
[Link]()
copy_alternate("[Link]", "[Link]")
Q11. Write a Python program to handle a ZeroDivisionError
exception when dividing a number by zero.
num = int(input("Enter a number: "))
result = None
print("We will try to divide your number by zero...")
try:
result = num / 0
print("Division successful! Result is:", result)
except ZeroDivisionError:
# This block runs when division by zero occurs
print("Error! You tried to divide by ZERO.")
print("Division by zero is not allowed in mathematics.")
# Step 4: Inform that program is still running
print("Program continues normally after handling the exception.")
OUTPUT of Question 11
Sample Input:
Enter numerator: 10
Enter denominator: 0
Program Output:
Cannot divide by zero! ZeroDivisionError occurred.
Another Input:
Enter numerator: 20
Enter denominator: 5
Program Output:
Result: 4.0
Q12. Write a program that reads a list of integers from the user and
throws an exception if any numbers are duplicates.
user_input = input("Enter integers separated by spaces: ")
numbers = user_input.split() # Creates list of strings
int_list = [] # Empty list for storing integers
for item in numbers:
value = int(item)
int_list.append(value)
seen_numbers = set()
duplicate_found = False
for num in int_list:
if num in seen_numbers: # Already present = duplicate found
duplicate_found = True
break
else:
seen_numbers.add(num) # Add to set because it is new
if duplicate_found == True:
raise Exception("Duplicate numbers detected! Please enter unique values only.")
else:
print("All numbers are unique. No duplicates found.")
OUTPUT of Question 12
Case 1: User enters UNIQUE numbers
Input:
Enter numbers separated by space: 1 2 3 4 5
Output:
All numbers are unique. List accepted.
Case 2: User enters DUPLICATE numbers
Input:
Enter numbers separated by space: 2 5 7 2 9
Output:
Duplicate numbers found! Exception: DuplicateEntryError: List contains duplicate
values.
Q13. Write a program that makes use of a function to display sine,
cosine, polynomial and exponential curves.
import numpy as np
import [Link] as plt
x = [Link](0, 10, 100)
def show_plots():
[Link](x, [Link](x))
[Link]("Sine Curve")
[Link]()
[Link](x, [Link](x))
[Link]("Cosine Curve")
[Link]()
[Link](x, x**2 + 2*x + 1)
[Link]("Polynomial Curve")
[Link]()
[Link](x, [Link](x))
[Link]("Exponential Curve")
[Link]()
show_plots()
OUTPUT of Question 13
Program Output:
Displaying Sine Curve...
Displaying Cosine Curve...
Displaying Polynomial Curve...
Displaying Exponential Curve...
Graphs generated successfully.
Q14. Take as input in the months and profits made by a company
ABC over a year. Represent this data using a line plot. Generated
line plot must include X axis label name = Month Number and Y
axis label name = Total profit."
import [Link] as plt
# Taking month numbers as input
month_input = input("Enter month numbers (1-12): ")
months = month_input.split()
# Convert months to integers
month_list = []
for m in months:
month_list.append(int(m))
# Taking profit values
profit_input = input("Enter profits for each month: ")
profit_parts = profit_input.split()
profits = []
for p in profit_parts:
[Link](int(p))
# Check if both lists match in length
if len(month_list) != len(profits):
print("Error: Number of months and profits must be equal.")
else:
# Plotting the graph
[Link](month_list, profits)
[Link]("Month Number")
[Link]("Total Profit")
[Link]("ABC Company Yearly Profit")
[Link]()
OUTPUT of Question 14
Since the program creates a line graph, here is the standard output shown on screen
before the graph window appears:
Enter profits for 12 months:
Plotting line graph...
Graph generated successfully.
Actual Result (Graph Window Shows):
A line plot appears with:
X-axis label: Month Number
Y-axis label: Total Profit
12 points plotted (one for each month)
A line connecting all profit values
Example (if input was):
10000 12000 9000 15000 17000 14000 16000 18000 20000 19000 21000 22000
Graph will show a rising & falling line based on these values.