Python Lab Record
1. Write a Program to show whether entered numbers are prime or not in
the given range.
2. Input a string and determine whether it is a palindrome or not.
3. Find the largest/smallest number in a list/tuple
4. WAP to input any two tuples and swap their values.
5. WAP to store students’ details like admission number, roll number,
name and percentage in a dictionary and display information on the
basis of admission number.
6. Write a program with a user-defined function with string as a parameter
which replaces all vowels in the string with ‘*’.
7. Recursively find the factorial of a natural number.
8. Write a recursive code to find the sum of all elements of a list.
9. Write a recursive code to compute the nth Fibonacci number.
10. Read a text file line by line and display each word separated by a #.
11. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase and other than character and digit in the file.
12. Write a Python code to find the size of the file in bytes, the number of
lines, number of words and no. of character.
13. Write a program that accepts a filename of a text file and reports the
file's longest line.
14. Create a binary file with the name and roll number. Search for a given
roll number and display the name, if not found display appropriate
message.
15. Create a binary file with roll number, name and marks. Input a roll
number and update details.
16. Remove all the lines that contain the character `a' in a file and write it
to another file.
17. Write a program to perform read and write operation onto a student.csv
file having fields as roll number, name, stream and percentage.
18. Program to search the record of a particular student from CSV file on
the basis of inputted name.
19. Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
20. Write a program to create a library in python and import it in a program.
21. Write a python program to implement sorting techniques based on user
choice using a list data-structure. (bubble/insertion)
22. Take a sample of ten phishing e-mails (or any text file) and find the
most commonly occurring word(s).
23. Write a python program to implement a stack using a list data-
structure.
24. Write a program to implement a queue using a list data structure.
25. Write a python program to implement searching methods based on user
choice using a list data-structure. (linear & binary)
Program 1: Primes in a Range
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
is_prime(n) checks whether integer n is prime.
First, if n ≤ 1, it's not prime (0, 1, negatives).
If n ≤ 3 (i.e. 2 or 3), it's prime.
If divisible by 2 or 3, it's not prime.
Then use a loop: check divisibility by i and i + 2 for successive i = 5, 11, 17, …
(this is a standard optimization for primality).
Loop condition i * i <= n ensures we only check divisors up to √n.
def primes_in_range(start, end):
primes = []
for x in range(start, end + 1):
if is_prime(x):
primes.append(x)
return primes
Iterates x from start to end inclusive.
Uses is_prime(x); if true, adds to list primes.
Returns the final list.
def main():
a = int(input("Enter start of range: "))
b = int(input("Enter end of range: "))
print("Primes in the range:", primes_in_range(a, b))
if __name__ == "__main__":
main()
main() handles user interaction.
Reads start and end of range from user, calls primes_in_range, then prints result.
The if __name__ == "__main__": guard ensures main() runs only if file is
executed directly, not when imported.
Program 2: Palindrome Check
def is_palindrome(s):
cleaned = ''.join(ch.lower() for ch in s if ch.isalnum())
return cleaned == cleaned[::-1]
Takes input string s.
cleaned is a lowercased version, stripping out non-alphanumeric characters (so punctuation
and spaces get removed). This makes palindrome check more robust.
Checks cleaned == cleaned[::-1]: reversed string comparison. If equal, it's a
palindrome.
def main():
s = input("Enter a string: ")
if is_palindrome(s):
print("It is a palindrome.")
else:
print("It is not a palindrome.")
if __name__ == "__main__":
main()
Reads a string, uses is_palindrome, prints the result.
Program 3: Largest / Smallest in List or Tuple
def find_largest(seq):
return max(seq)
def find_smallest(seq):
return min(seq)
find_largest returns the maximum element in seq (list or tuple).
find_smallest returns minimum.
def main():
raw = input("Enter numbers separated by spaces: ")
lst = [float(x) for x in raw.split()]
print("Largest:", find_largest(lst))
print("Smallest:", find_smallest(lst))
if __name__ == "__main__":
main()
Reads a space-separated line of numbers from user.
Converts each to float.
Prints largest and smallest.
Program 4: Swap Two Tuples
def swap_tuples(t1, t2):
return t2, t1
Simply returns a tuple pair (t2, t1), effectively swapping.
def main():
t1 = tuple(input("Enter first tuple items (space-separated):
").split())
t2 = tuple(input("Enter second tuple items (space-separated):
").split())
new1, new2 = swap_tuples(t1, t2)
print("After swap:")
print("First tuple:", new1)
print("Second tuple:", new2)
if __name__ == "__main__":
main()
Reads two lines of input, splits into items, creates tuples.
Swaps them, prints result.
Program 5: Student Details in Dictionary
def add_student(students, adm_no, roll, name, percentage):
students[adm_no] = {
'roll': roll,
'name': name,
'percentage': percentage
}
def get_student(students, adm_no):
return students.get(adm_no)
students is a dictionary keyed by adm_no (admission number).
add_student inserts a record dictionary for that admission number.
get_student tries to fetch the record; returns None if not found.
def main():
students = {}
n = int(input("How many students to add? "))
for _ in range(n):
adm = input("Admission no: ")
roll = input("Roll no: ")
nm = input("Name: ")
pct = float(input("Percentage: "))
add_student(students, adm, roll, nm, pct)
search = input("Enter admission number to look up: ")
result = get_student(students, search)
if result:
print("Details for admission", search, ":", result)
else:
print("No student with that admission number.")
if __name__ == "__main__":
main()
Builds the students dictionary from user input.
Then allows user to search by admission number and prints details if found.