Computer_Science_Practical_File (2) (1)
Computer_Science_Practical_File (2) (1)
EXCEPTION HANDLING
1. Division by Zero
Program:
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Error: Division by zero.")
Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero.
2. Index Error
Program:
try:
lst = [1, 2, 3]
print(lst[5])
except IndexError:
print("Index out of range!")
Output:
3. Value Error
Program:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Invalid input! Not an integer.")
Output:
4. Multiple Exceptions
Program:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
Output:
Enter a: ten
Invalid input.
5. Finally Block
Program:
try:
num = int(input("Enter a number: "))
print("Square:", num * num)
finally:
print("This block always runs.")
Output:
Enter a number: 5
Square: 25
This block always runs.
Hello, World!
3. Append to a File
Program:
Total lines: 2
word = "Python"
with open("sample.txt", "r") as f:
found = any(word in line for line in f)
print("Found" if found else "Not Found")
Output:
Found
STACK
stack = []
stack.append(10)
stack.append(20)
print("Stack:", stack)
print("Popped:", stack.pop())
Output:
def pop(stack):
return stack.pop()
stack = []
push(stack, 1)
push(stack, 2)
print("Stack:", stack)
print("Popped:", pop(stack))
Output:
Stack: [1, 2]
Popped: 2
stack = []
limit = 3
for i in range(5):
if len(stack) < limit:
stack.append(i)
else:
print("Stack Overflow")
Output:
Stack Overflow
Stack Overflow
SORTING
1. Bubble Sort
Program:
arr = [5, 2, 9, 1]
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("Sorted array:", arr)
Output:
2. Insertion Sort
Program:
3. Selection Sort
Program:
a = [1, 3, 5]
b = [2, 4, 6]
merged = sorted(a + b)
print("Merged:", merged)
Output:
Merged: [1, 2, 3, 4, 5, 6]
arr = [1, 4, 1, 2, 7, 5, 2]
max_val = max(arr)
count = [0] * (max_val + 1)
for num in arr:
count[num] += 1
sorted_arr = []
for i in range(len(count)):
sorted_arr.extend([i] * count[i])
print("Sorted:", sorted_arr)
Output:
Sorted: [1, 1, 2, 2, 4, 5, 7]