# =============================================================================
# PRACTICAL 1: Check if a number is palindrome or not
# =============================================================================
CODE:
a=input("Enter a string")
if (str(a)==str(a)[::-1]):
print ("Palindrome")
else:
print("Not palindrome")
OUTPUT:
# =============================================================================
# PRACTICAL 2: Display ASCII code of character and vice versa
# =============================================================================
CODE:
print("""Choice\t
1\t Chr to ascii
2\t ascii to chr""")
c = int(input("Enter your choice: "))
if c == 1:
cr = input("Enter a character: ")
m = ord(cr)
print("ASCII value is", m)
elif c == 2: # Changed 'ch' to 'c'
n = int(input("Enter an ASCII value: "))
m = chr(n)
print("Character is", m)
else:
print("Enter a valid choice")
OUTPUT:
# =============================================================================
# PRACTICAL 3: Sum the series 1+1/1!+1/2!+1/3!+...+1/n!
# =============================================================================
CODE:
n = int(input("Enter the value of n: "))
sum_series = 1
factorial = 1
for i in range(1, n + 1):
factorial = factorial * i
sum_series = sum_series + (1 / factorial)
print(f"Sum of the series up to {n} terms: {sum_series}")
OUTPUT:
# =============================================================================
# PRACTICAL 4: Calculate factorial using recursion
# =============================================================================
CODE:
print("PRACTICAL 4: Factorial using recursion")
def factorial_recursive(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
num = int(input("Enter a number: "))
result = factorial_recursive(num)
print(f"Factorial of {num} is {result}")
OUTPUT:
# =============================================================================
# PRACTICAL 5: Sum of all elements in list using recursion
# =============================================================================
CODE:
def sum_list_recursive(lst):
if len(lst) == 0:
return 0
else:
return lst[0] + sum_list_recursive(lst[1:])
user_input = input("Enter numbers separated by spaces: ")
numbers = list(map(int, user_input.split()))
print(f"List: {numbers}")
total = sum_list_recursive(numbers)
print(f"Sum of all elements: {total}")
OUTPUT:
# =============================================================================
# PRACTICAL 6: Fibonacci series using recursion
# =============================================================================
CODE:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = int(input("Enter number of terms: "))
print("Fibonacci series:")
for i in range(n):
print(fibonacci(i), end=" ")
print()
OUTPUT:
# =============================================================================
# PRACTICAL 7: Binary search using recursion
# =============================================================================
CODE:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
arr = [2, 3, 4, 10, 40]
x = int(input("Enter element to search: "))
result = binary_search(arr, 0, len(arr) - 1, x)
if result != -1:
print(f"Element is present at index {result}")
else:
print("Element is not present in array")
OUTPUT:
# =============================================================================
# PRACTICAL 8: Check if string is palindrome using recursion
# =============================================================================
CODE:
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
string = input("Enter a string: ")
if is_palindrome(string.lower()):
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")
OUTPUT:
# =============================================================================
# PRACTICAL 9: Read text file and display words separated by '#'
# =============================================================================
CODE:
with open("file1.txt", "w") as f:
f.write("Hello world\n")
f.write("Python programming\n")
f.write("Online compiler test\n")
with open("file1.txt", "r") as f:
for line in f:
words = line.split()
for w in words:
print(w + '#', end="")
print()
OUTPUT:
# =============================================================================
# PRACTICAL 10: Count vowels in text file
# =============================================================================
CODE:
with open("sample.txt", "w") as f:
f.write("Hello world\n")
f.write("Python programming\n")
f.write("Online compiler test\n")
vowels = "aeiouAEIOU"
vowel_count = 0
with open("sample.txt", "r") as f:
content = f.read()
for char in content:
if char in vowels:
vowel_count += 1
print(f"Number of vowels in file: {vowel_count}")
OUTPUT:
# =============================================================================
# PRACTICAL 11: Count words in file
# =============================================================================
CODE:
with open("sample.txt", "w") as f:
f.write("Hello world\n")
f.write("Python programming\n")
f.write("Online compiler test\n")
word_count = 0
with open("sample.txt", "r") as f:
for line in f:
words = line.strip().split()
word_count += len(words)
print(f"Number of words in file: {word_count}")
OUTPUT:
# =============================================================================
# PRACTICAL 12: Count occurrences of 'is' in file
# =============================================================================
CODE:
with open("sample.txt", "w") as f:
f.write("Hello world\n")
f.write("Python is a programming\n")
f.write("Online compiler test\n")
count = 0
with open("sample.txt", "r") as f:
content = f.read().lower()
words = content.split()
for word in words:
if word == "is":
count += 1
print(f"Number of times 'is' appears: {count}")
OUTPUT:
# =============================================================================
# PRACTICAL 13: Copy lines containing 'p' to another file
# ============================================================================
CODE:
File1 = open("source.txt", "w")
file1.write("This is a simple line\n")
file1.write("Python programming is fun\n")
file1.write("We are learning file handling\n")
file1.write("Computer applications are useful\n")
file1.write("Keep practicing everyday\n")
file1.close()
file1 = open("source.txt", "r")
file2 = open("destination.txt", "w")
for line in file1:
if 'p' in line or 'P' in line:
file2.write(line)
print("Copied:", line.strip())
file1.close()
file2.close()
OUTPUT:
#=============================================================================
# PRACTICAL 14: Create and read binary file with student data
# =============================================================================
CODE:
import pickle
students = [
{"name": "Alice", "roll": 101},
{"name": "Bob", "roll": 102},
{"name": "Charlie", "roll": 103}
with open("students.dat", "wb") as file:
pickle.dump(students, file)
with open("students.dat", "rb") as file:
data = pickle.load(file)
print("Student data:")
for student in data:
print(f"Name: {student['name']}, Roll: {student['roll']}")
OUTPUT:
# =============================================================================
# PRACTICAL 15: Search student record by roll number
# =============================================================================
CODE:
#Sample data
students = [
{"name": "Rahul Sharma", "roll": 101},
{"name": "Priya Singh", "roll": 102},
{"name": "Amit Kumar", "roll": 103},
{"name": "Sneha Patel", "roll": 104},
{"name": "Rohit Gupta", "roll": 105}
import pickle
with open("students.dat", "wb") as file:
pickle.dump(students, file)
""" sample dataif you want to print ----> for student in students:
print(f"Roll: {student['roll']}, Name: {student['name']}")"""
roll_to_find = int(input("\nEnter roll number to search: "))
found = False
with open("students.dat", "rb") as file:
data = pickle.load(file)
for student in data:
if student['roll'] == roll_to_find:
print(f"Student found - Name: {student['name']}")
found = True
break
if not found:
print("Student record not found")
OUTPUT:
# =============================================================================
# PRACTICAL 16: Update student name by roll number
# =============================================================================
CODE:
students = [
{"name": "Rahul Sharma", "roll": 101},
{"name": "Priya Singh", "roll": 102},
{"name": "Amit Kumar", "roll": 103},
{"name": "Sneha Patel", "roll": 104},
{"name": "Rohit Gupta", "roll": 105}
import pickle
with open("students.dat", "wb") as file:
pickle.dump(students, file)
print("Current student data:")
for student in students:
print(f"Roll: {student['roll']}, Name: {student['name']}")
# Update student name
roll_to_update = int(input("\nEnter roll number to update: "))
new_name = input("Enter new name: ")
with open("students.dat", "rb") as file:
data = pickle.load(file)
updated = False
for student in data:
if student['roll'] == roll_to_update:
old_name = student['name']
student['name'] = new_name
updated = True
print(f"Updated: {old_name} -> {new_name}")
break
if updated:
with open("students.dat", "wb") as file:
pickle.dump(data, file)
print("Record updated successfully")
else:
print("Record not found")
OUTPUT:
# =============================================================================
# PRACTICAL 17: Delete record from binary file
# =============================================================================
CODE:
students = [
{"name": "Rahul Sharma", "roll": 101},
{"name": "Priya Singh", "roll": 102},
{"name": "Amit Kumar", "roll": 103},
{"name": "Sneha Patel", "roll": 104},
{"name": "Rohit Gupta", "roll": 105}
import pickle
with open("students.dat", "wb") as file:
pickle.dump(students, file)
print("Current student data:")
for student in students:
print(f"Roll: {student['roll']}, Name: {student['name']}")
roll_to_delete = int(input("\nEnter roll number to delete: "))
with open("students.dat", "rb") as file:
data = pickle.load(file)
new_data = []
deleted = False
deleted_name = ""
for student in data:
if student['roll'] != roll_to_delete:
new_data.append(student)
else:
deleted = True
deleted_name = student['name']
if deleted:
with open("students.dat", "wb") as file:
pickle.dump(new_data, file)
print(f"Record deleted successfully: {deleted_name} (Roll: {roll_to_delete})")
print("\nRemaining student data:")
for student in new_data:
print(f"Roll: {student['roll']}, Name: {student['name']}")
else:
print("Record not found")
OUTPUT:
#=============================================================================
# PRACTICAL 18: Read and write CSV file
# =============================================================================
CODE:
import csv
data = [
['Name', 'Age', 'City'],
['John', 25, 'New York'],
['Jane', 30, 'London'],
['Bob', 35, 'Paris']
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
print("Data written to CSV file")
print(data)
OUTPUT:
#=============================================================================
# PRACTICAL 19: Random number generator and lottery checker
# =============================================================================
CODE:
import random
number = random.randint(1, 6)
guess = int(input("Enter your guess (1-6): "))
print("Winning number:", number)
if guess == number:
print("You won!")
else:
print("You lost!")
OUTPUT:
# =============================================================================
# PRACTICAL 20: Create a library and import it
# =============================================================================
CODE:
library_content = '''
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero"
'''
with open("mylib.py", "w") as file:
file.write(library_content)
import mylib
a = int(input("Enter a no."))
b = int(input("Enter a no."))
print(f"Addition: {mylib.add(a, b)}")
print(f"Subtraction: {mylib.subtract(a, b)}")
print(f"Multiplication: {mylib.multiply(a, b)}")
print(f"Division: {mylib.divide(a, b)}")
OUTPUT:
# =============================================================================
# PRACTICAL 21: Linear search
# =============================================================================
CODE:
arr = [64, 34, 25, 12, 22, 11, 90]
target = int(input("Enter element to search: "))
found = False
position = -1
for i in range(len(arr)):
if arr[i] == target:
found = True
position = i
break
if found:
print(f"Element {target} found at position {position}")
else:
print(f"Element {target} not found")
OUTPUT:
# =============================================================================
# PRACTICAL 22: Bubble sort
# =============================================================================
CODE:
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Original array: {arr}")
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(f"Sorted array: {arr}")
OUTPUT:
# =============================================================================
# PRACTICAL 23: Stack operations menu
# =============================================================================
CODE:
stack = [1,2,3,4,5,6,7,8,9,10]
while True:
print("\nStack Menu:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
element = input("Enter element to push: ")
stack.append(element)
print(f"Pushed {element}")
elif choice == '2':
if stack:
popped = stack.pop()
print(f"Popped {popped}")
else:
print("Stack is empty")
elif choice == '3':
if stack:
print(f"Stack: {stack}")
else:
print("Stack is empty")
elif choice == '4':
break
else:
print("Invalid choice")
OUTPUT:
# =============================================================================
# PRACTICAL 24: Queue operations menu
# =============================================================================
CODE:
queue = [23.23,234,436,6542,752,244]
while True:
print("\nQueue Menu:")
print("1. Enqueue")
print("2. Dequeue")
print("3. Display")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
element = input("Enter element to enqueue: ")
queue.append(element)
print(f"Enqueued {element}")
elif choice == '2':
if queue:
dequeued = queue.pop(0)
print(f"Dequeued {dequeued}")
else:
print("Queue is empty")
elif choice == '3':
if queue:
print(f"Queue: {queue}")
else:
print("Queue is empty")
elif choice == '4':
break
else:
print("Invalid choice")
OUTPUT:
# =============================================================================
# PRACTICAL 25: Find most common words in a file
# =============================================================================
CODE:
sample_text = """Python is a programming language. Python is easy to learn.
Programming with Python is fun and Python is powerful.
Many students learn Python because Python is popular.
Python programming helps in data science and Python is versatile.
Learning Python is the best way to start programming."""
with open("sample_text.txt", "w") as file:
file.write(sample_text)
# Count word frequency
word_count = {}
with open("sample_text.txt", "r") as file:
content = file.read().lower()
words = content.split()
for word in words:
# Remove punctuation
word = word.strip('.,!?;:"()')
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("\nWord frequency count:",end=" ")
for word, count in word_count.items():
print(f"{word}: {count}", end=",")
# Find most common words
if word_count:
max_count = max(word_count.values())
most_common = []
for word, count in word_count.items():
if count == max_count:
most_common.append(word)
print(f"\nMost common word(s): {most_common}",end=" ")
print(f"Frequency: {max_count}",end=" ")
else:
print("No words found in file")
OUTPUT: