0% found this document useful (0 votes)
5 views11 pages

Def Print

The document contains multiple Python programs aimed at various tasks including printing file lines in reverse, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different geometric shapes. Each program includes a clear aim, structured functions, and user input handling. The programs showcase fundamental programming concepts such as file handling, loops, and object-oriented programming.
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)
5 views11 pages

Def Print

The document contains multiple Python programs aimed at various tasks including printing file lines in reverse, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different geometric shapes. Each program includes a clear aim, structured functions, and user input handling. The programs showcase fundamental programming concepts such as file handling, loops, and object-oriented programming.
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/ 11

PYTHON UNIT 4

AIM: Python program to print each line of a file in reverse order


Program:

def print_lines_in_reverse(file_path):
try:
with open(file_path, 'r') as file:
lines = file.readlines()
for line in reversed(lines):
print(line.strip())
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
file_path = input("Enter the path to the file: ")
print_lines_in_reverse(file_path)
PYTHON UNIT 4

AIM: Python program to compute the number of characters, words


and lines in a file
Program:
file_path = input("Enter the path to the file: ")

try:

with open(file_path, 'r') as file:

content = file.read() # Read the entire file content

num_lines = content.count('\n') + 1 # Count lines

num_words = len(content.split()) # Count words

num_chars = len(content) # Count characters

print(file_path)

print(f"Number of lines: {num_lines}")

print(f"Number of words: {num_words}")

print(f"Number of characters: {num_chars}")

except FileNotFoundError:

print(f"The file {file_path} does not exist.")

except Exception as e:

print(f"An error occurred: {e}")


PYTHON UNIT 4
AIM: Write a program to create, display, append, insert and reverse
the order of the items in the array.

Program:
# Initialize an empty list (array)

array = []

def display_array(arr):

print("Current array:", arr)

while True:

print("\nMenu:")

print("1. Create an array")

print("2. Display the array")

print("3. Append an item")

print("4. Insert an item")

print("5. Reverse the array")

print("6. Exit")

choice = input("Choose an option (1-6): ")

if choice == '1':

array = input("Enter items separated by space: ").split()

print("Array created.")

elif choice == '2':

display_array(array)

elif choice == '3':


PYTHON UNIT 4
item = input("Enter an item to append: ")

array.append(item)

print(f"'{item}' appended to the array.")

elif choice == '4':

item = input("Enter an item to insert: ")

position = int(input("Enter the position to insert (0 to {}):


".format(len(array))))

if 0 <= position <= len(array):

array.insert(position, item)

print(f"'{item}' inserted at position {position}.")

else:

print("Invalid position.")

elif choice == '5':

array.reverse()

print("Array reversed.")

elif choice == '6':

# Exit

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")


PYTHON UNIT 4

AIM: Write a program to add, transpose and multiply two matrices

Program:
def get_matrix_input(rows, cols):

matrix = []

print(f"Enter the elements of the matrix ({rows}x{cols}):")

for i in range(rows):

row = list(map(int, input(f"Row {i + 1}: ").split()))

while len(row) != cols:

print(f"Please enter exactly {cols} numbers.")

row = list(map(int, input(f"Row {i + 1}: ").split()))

matrix.append(row)

return matrix

def add_matrices(A, B):

return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]

def transpose_matrix(matrix):

return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

def multiply_matrices(A, B):

result = [[0] * len(B[0]) for _ in range(len(A))]

for i in range(len(A)):

for j in range(len(B[0])):

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]


PYTHON UNIT 4
return result

def display_matrix(matrix):

for row in matrix:

print(' '.join(map(str, row)))

# Main program

while True:

print("\nMenu:")

print("1. Add matrices")

print("2. Transpose a matrix")

print("3. Multiply matrices")

print("4. Exit")

choice = input("Choose an option (1-4): ")

if choice == '1':

rows = int(input("Enter number of rows: "))

cols = int(input("Enter number of columns: "))

print("Matrix A:")

A = get_matrix_input(rows, cols)

print("Matrix B:")

B = get_matrix_input(rows, cols)

result = add_matrices(A, B)

print("Result of addition:")

display_matrix(result)
PYTHON UNIT 4
elif choice == '2':

rows = int(input("Enter number of rows: "))

cols = int(input("Enter number of columns: "))

print("Matrix:")

matrix = get_matrix_input(rows, cols)

result = transpose_matrix(matrix)

print("Transposed matrix:")

display_matrix(result)

elif choice == '3':

rows_A = int(input("Enter number of rows for Matrix A: "))

cols_A = int(input("Enter number of columns for Matrix A: "))

print("Matrix A:")

A = get_matrix_input(rows_A, cols_A)

rows_B = int(input("Enter number of rows for Matrix B: "))

cols_B = int(input("Enter number of columns for Matrix B: "))

if cols_A != rows_B:

print("Error: Number of columns in Matrix A must be equal to number


of rows in Matrix B.")

continue

print("Matrix B:")

B = get_matrix_input(rows_B, cols_B)

result = multiply_matrices(A, B)
PYTHON UNIT 4
print("Result of multiplication:")

display_matrix(result)

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")

AIM: Write a Python program to create a class that represents a


shape. Include methods to calculate its area and perimeter.
PYTHON UNIT 4
Implement subclasses for different shapes like circle,triangle, and
square.
Program:
import math

# Base class

class Shape:

def area(self):

raise NotImplementedError("Area method must be implemented by


subclasses.")

def perimeter(self):

raise NotImplementedError("Perimeter method must be implemented by


subclasses.")

# Circle subclass

class Circle(Shape):

def __init__(self, radius):

self.radius = radius

def area(self):

return math.pi * (self.radius ** 2)

def perimeter(self):

return 2 * math.pi * self.radius

# Triangle subclass

class Triangle(Shape):

def __init__(self, base, height, side1, side2):

self.base = base

self.height = height
PYTHON UNIT 4
self.side1 = side1

self.side2 = side2

def area(self):

return 0.5 * self.base * self.height

def perimeter(self):

return self.base + self.side1 + self.side2

# Square subclass

class Square(Shape):

def __init__(self, side):

self.side = side

def area(self):

return self.side ** 2

def perimeter(self):

return 4 * self.side

# Main program

def main():

shapes = []

# Create a circle

radius = float(input("Enter the radius of the circle: "))

shapes.append(Circle(radius))

# Create a triangle

base = float(input("Enter the base of the triangle: "))


PYTHON UNIT 4
height = float(input("Enter the height of the triangle: "))

side1 = float(input("Enter the length of side 1 of the triangle: "))

side2 = float(input("Enter the length of side 2 of the triangle: "))

shapes.append(Triangle(base, height, side1, side2))

# Create a square

side = float(input("Enter the side length of the square: "))

shapes.append(Square(side))

# Display areas and perimeters

for shape in shapes:

print(f"\nShape: {shape.__class__.__name__}")

print(f"Area: {shape.area():.2f}")

print(f"Perimeter: {shape.perimeter():.2f}")

if __name__ == "__main__":

main()

You might also like