0% found this document useful (0 votes)
4 views22 pages

Python Answers

The document provides Python programming examples covering various topics such as turtle graphics for drawing shapes, image processing for converting color images to grayscale, and GUI programming with tkinter for creating user interfaces. It also explains NumPy functions like arange(), reshape(), and linspace(), along with indexing and slicing in NumPy arrays, and demonstrates exception handling and object-oriented programming with a Car class. Each section includes code examples and explanations to illustrate the concepts effectively.

Uploaded by

wimihob958
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Python Answers

The document provides Python programming examples covering various topics such as turtle graphics for drawing shapes, image processing for converting color images to grayscale, and GUI programming with tkinter for creating user interfaces. It also explains NumPy functions like arange(), reshape(), and linspace(), along with indexing and slicing in NumPy arrays, and demonstrates exception handling and object-oriented programming with a Car class. Each section includes code examples and explanations to illustrate the concepts effectively.

Uploaded by

wimihob958
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Answer Based on PDFs

Module 3 Programming in Python PDF Notes - Kerala [Link]


PDF

Module 4 Programming in Python Notes - Kerala [Link]


PDF

Module 5 Programming in Python PDF Notes - Kerala [Link]


PDF
answer the question based on this use it for reference

I have received your reference PDFs:

Programming in Python – Module 3 (Graphics)


Module 3 Programming in Python …

Programming in Python – Module 4 (OOP Concepts)


Module 4 Programming in Python …

Programming in Python – Module 5 (NumPy, OS, Matplotlib, Pandas, etc.)


Module 5 Programming in Python …

I will answer your questions strictly based on these PDFs and use them as reference for the
explanations.

✅ Please send the question(s) you want me to answer.


Sources

Write a python program to draw ANY SHAPE(circle,star, hexagon or rectangle) using turtle and
fill with any colour

Python Program to Draw a Shape Using Turtle and Fill with Color

Turtle graphics is a simple Python graphics library used to draw shapes by moving a turtle (cursor) on
the screen using commands like forward(), left(), right(), etc. The turtle draws lines when the pen is
down and moves without drawing when the pen is up.
Module 3 Programming in Python …
Below is a Python program that draws a hexagon and fills it with color.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/22
import turtle

# Create turtle object


t = [Link]()

# Set color
[Link]("black", "blue") # outline color, fill color

# Start filling the shape


t.begin_fill()

# Draw hexagon
for i in range(6):
[Link](100)
[Link](60)

# Stop filling
t.end_fill()

# Finish
[Link]()

Explanation

import turtle → imports the turtle graphics module.

[Link]() → creates a turtle object used for drawing.

color("black","blue") → sets the outline color and fill color.


begin_fill() and end_fill() → used to fill the shape with the specified color.

forward(100) → moves the turtle forward by 100 units.

left(60) → turns the turtle 60° to draw the hexagon.

When the program runs, a hexagon filled with blue color will be drawn on the screen.

✅ If you want, I can also give programs for circle, star, and rectangle (sometimes exams ask any one
of them).
Sources

Write a python program to converting a color image to a grayscale image.

Python Program to Convert a Color Image to a Grayscale Image

In image processing, an image is represented as a grid of pixels, and each pixel contains a color value
represented by RGB components (Red, Green, Blue). A grayscale image is obtained by converting these
RGB values into a single intensity value.
Module 3 Programming in Python …

Below is a Python program that converts a color image into a grayscale image.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/22
from images import Image

# Load the image


image = Image("[Link]")

# Get width and height of the image


width = [Link]()
height = [Link]()

# Convert to grayscale
for x in range(width):
for y in range(height):
(r, g, b) = [Link](x, y)

# Calculate grayscale value


gray = (r + g + b) // 3

# Set new grayscale pixel


[Link](x, y, (gray, gray, gray))

# Display the grayscale image


[Link]()

Explanation

Image("[Link]") → loads the color image file.


getWidth() and getHeight() → return the image dimensions.

getPixel(x,y) → retrieves the RGB values of each pixel.

gray = (r+g+b)//3 → computes the grayscale intensity.

setPixel(x,y,(gray,gray,gray)) → replaces the color pixel with grayscale.


[Link]() → displays the grayscale image.

This program reads every pixel of the image, converts its RGB value into a grayscale value, and updates
the image accordingly.
Sources

Design a Python GUI program(eg:- login page or area of a shape)

Python GUI Program – Area of a Rectangle

A GUI (Graphical User Interface) program displays information graphically using components like
labels, entry fields, and command buttons. A GUI program is event-driven, which means it waits for
the user to click a button or perform an action.
Module 3 Programming in Python … Module 3 Programming in Python …

According to the notes, a GUI program is usually designed by:

1. defining the main window,

2. adding components such as labels, fields, and buttons,


3. positioning them,

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/22
4. and defining the method that handles the button click event.
Module 3 Programming in Python …

Module 3 Programming in Python …

Below is a simple Python GUI program to find the area of a rectangle using tkinter.
from tkinter import *

def calculate_area():
l = float(length_entry.get())
b = float(breadth_entry.get())
area = l * b
result_label.config(text="Area = " + str(area))

root = Tk()
[Link]("Area of Rectangle")
[Link]("300x200")

Label(root, text="Enter Length").pack()


length_entry = Entry(root)
length_entry.pack()

Label(root, text="Enter Breadth").pack()


breadth_entry = Entry(root)
breadth_entry.pack()

Button(root, text="Calculate Area", command=calculate_area).pack(pady=10)

result_label = Label(root, text="Area = ")


result_label.pack()

[Link]()

Explanation

Tk() creates the main window.


Label is used to display text.

Entry is used to accept user input.


Button is used to perform an action when clicked.
calculate_area() is the event-handling function.

[Link]() keeps the window active.

Output

The program opens a GUI window with:

two input boxes for length and breadth,

one Calculate Area button,


and a label to display the result.

If you want, I can also write a GUI login page program in the same exam style.
Sources

display an image with a caption using Python in a graphical interface

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/22
Python Program to Display an Image with a Caption (GUI)

In image processing with Python, an image can be loaded from a file and displayed in a window using
graphical tools. The images module allows a programmer to load an image, display it in a window, and
manipulate it.
Module 3 Programming in Python …

Below is a simple Python GUI program to display an image with a caption using tkinter.
from tkinter import *
from PIL import Image, ImageTk

# Create main window


root = Tk()
[Link]("Image Display")

# Load image
img = [Link]("[Link]")
photo = [Link](img)

# Display image
label_image = Label(root, image=photo)
label_image.pack()

# Caption
caption = Label(root, text="Beautiful Nature", font=("Arial", 14))
[Link]()

# Run the GUI


[Link]()

Explanation

Tk() → creates the GUI window.

[Link]() → loads the image file.


[Link]() → converts the image for displaying in Tkinter.

Label(root, image=photo) → displays the image.


Label(root, text="Beautiful Nature") → displays the caption below the image.
mainloop() → keeps the window running.

Output

The program opens a GUI window that shows an image with a caption displayed below it.

Sources

. Explain the use of arange(), reshape(), and linspace() functions in NumPy

1. arange() Function in NumPy

arange()is used to create an array with evenly spaced values within a given interval. It works similar
to Python’s range() function but returns a NumPy array.

Syntax

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/22
[Link](start, stop, step)

Example
import numpy as np
a = [Link](0, 10, 2)
print(a)

Output
[0 2 4 6 8]

Explanation

start → starting value

stop → ending value (not included)


step → interval between values

This function is commonly used to generate sequences of numbers for numerical computations.

Module 5 Programming in Python …

2. reshape() Function in NumPy

reshape() is used to change the shape or dimensions of an array without changing its data.
Syntax
[Link](rows, columns)

Example
import numpy as np
a = [Link](6)
b = [Link](2,3)
print(b)

Output
[[0 1 2]
[3 4 5]]

Explanation

Converts a 1-D array into a 2-D array.


The total number of elements must remain the same.

3. linspace() Function in NumPy

linspace() is used to generate a specified number of evenly spaced values between two numbers.

Syntax
[Link](start, stop, num)

Example
import numpy as np
a = [Link](0, 10, 5)
print(a)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/22
Output
[0. 2.5 5. 7.5 10.]

Explanation

start → starting value

stop → ending value (included)


num → number of values to generate

Key Points

arange() → generates numbers with a fixed step size.


reshape() → changes the shape of an array.

linspace() → generates evenly spaced numbers based on the number of elements required.
Sources

the types of window components and their functions.

Types of Window Components and Their Functions

In a Python GUI (using Tkinter), window components are called widgets. These components are used to
create graphical interfaces where users can interact with the program.

1. Label

Used to display text or images on the window.

It is not used for user input.

Example
Label(root, text="Enter Name")

Function: Displays information such as instructions, titles, or messages.

2. Entry

Used to accept single-line text input from the user.

Example
Entry(root)

Function: Allows the user to enter data such as username, password, or numbers.

3. Button

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/22
Used to perform an action when clicked.

Example
Button(root, text="Submit", command=function_name)

Function: Executes a function when the user presses the button.

4. Text

Used to accept or display multi-line text.

Example
Text(root, height=5, width=30)

Function: Allows users to input or display multiple lines of text.

5. Checkbutton

Used to select or deselect an option.

Example
Checkbutton(root, text="Accept Terms")

Function: Lets the user choose options that can have multiple selections.

6. Radiobutton

Used to select one option from a group.

Example
Radiobutton(root, text="Male", value=1)

Function: Allows only one option to be selected from several choices.

7. Frame

Used to organize and group other widgets.

Example
Frame(root)

Function: Helps structure the layout of the GUI.

Summary

Window components (widgets) such as Label, Entry, Button, Text, Checkbutton, Radiobutton, and
Frame are used to create user interfaces. Each component performs a specific function like displaying
text, receiving input, or triggering actions.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/22
Explain indexing and slicing in NumPy arrays

Indexing and Slicing in NumPy Arrays

NumPy arrays allow access to elements using indexing and slicing, similar to Python lists. These
techniques help retrieve or modify specific elements or portions of an array.
Module 5 Programming in Python …

1. Indexing in NumPy
Indexing is used to access a single element from an array using its position.

NumPy arrays use zero-based indexing.


The first element has index 0, the second 1, and so on.

Example
import numpy as np

A = [Link](10)
print(A)
print(A[0])
print(A[-1])

Output
[0 1 2 3 4 5 6 7 8 9]
0
9

Explanation

A[0] → accesses the first element.

A[-1] → accesses the last element.

2. Slicing in NumPy
Slicing is used to access multiple elements from an array by specifying a range.

Syntax
array[start : end : step]

start → starting index

end → ending index (not included)

step → interval between elements

Example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/22
import numpy as np

A = [Link](10)

print(A[0:3])
print(A[5:])
print(A[:4])
print(A[::-1])

Output
[0 1 2]
[5 6 7 8 9]
[0 1 2 3]
[9 8 7 6 5 4 3 2 1 0]

Explanation

A[0:3] → elements from index 0 to 2.

A[5:] → elements from index 5 to the end.


A[:4] → elements from start to index 3.

A[::-1] → reverses the array.

Important Point
In NumPy, slices are views of the original array, meaning changes in the slice will affect the original
array.
Module 5 Programming in Python …

Example
slice = A[5:9]
slice[:] = 200
print(A)

Output
[0 1 2 3 4 200 200 200 200 9]

Summary

Indexing → accesses a single element of an array.


Slicing → accesses a group of elements using a range.

NumPy slicing returns a view, so modifications affect the original array.


Sources

Write a Python program to demonstrate exception

Python Program to Demonstrate Exception Handling

Exception handling is used to handle errors that occur during program execution so that the
program does not crash. In Python, exceptions are handled using try, except, and finally blocks.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/22
Module 4 Programming in Python …

Example Program
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

result = a / b
print("Result =", result)

except ZeroDivisionError:
print("Error: Division by zero is not allowed")

except ValueError:
print("Error: Invalid input")

finally:
print("Program execution completed")

Explanation

try block → contains the code that may cause an exception.

except block → handles the error if it occurs.

ZeroDivisionError → occurs when dividing a number by zero.


ValueError → occurs when invalid input is given.

finally block → executes whether an exception occurs or not.

Output Example
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed
Program execution completed

This program demonstrates how Python handles runtime errors using exception handling.
Sources

Write a Python program to create an instance of the Car class and demonstrate how to access
and modify its attributes

Python Program to Create an Instance of a Car Class and Access/Modify Attributes

In Object-Oriented Programming, a class is a blueprint for creating objects, and an object is an instance
of that class. Attributes (data members) store information related to the object, and they can be
accessed or modified using the object name.
Module 4 Programming in Python …

Example Program

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/22
class Car:
def __init__(self, brand, model, year):
[Link] = brand
[Link] = model
[Link] = year

def display(self):
print("Brand:", [Link])
print("Model:", [Link])
print("Year:", [Link])

# Create an instance (object) of Car class


car1 = Car("Toyota", "Corolla", 2022)

# Access attributes
print("Car Brand:", [Link])
print("Car Model:", [Link])

# Modify attributes
[Link] = 2024

# Display updated details


[Link]()

Explanation

class Car: → defines a class named Car.


__init__() → constructor used to initialize object attributes.

[Link], [Link], [Link] → instance variables of the class.


car1 = Car("Toyota","Corolla",2022) → creates an object of the class.

[Link] → accesses the attribute.


[Link] = 2024 → modifies the attribute value.

Sample Output
Car Brand: Toyota
Car Model: Corolla
Brand: Toyota
Model: Corolla
Year: 2024

This program demonstrates creating an object, accessing attributes, and modifying them in a class.
Sources

Demonstrate polymorphism by calling the area calculation method on instances of both


subclasses.

Demonstrating Polymorphism in Python (Area Calculation)

Polymorphism means the ability of different classes to respond to the same method name in different
ways. In object-oriented programming, different objects can implement the same method but perform
different actions.
Module 4 Programming in Python …

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/22
Below is a Python program where Rectangle and Circle classes both implement an area() method.
Calling the same method on different objects demonstrates polymorphism.

Python Program
import math

class Shape:
def area(self):
pass

class Rectangle(Shape):
def __init__(self, length, breadth):
[Link] = length
[Link] = breadth

def area(self):
return [Link] * [Link]

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * [Link] * [Link]

# Create objects of subclasses


rect = Rectangle(10, 5)
cir = Circle(7)

# Polymorphism: calling same method for different objects


print("Area of Rectangle:", [Link]())
print("Area of Circle:", [Link]())

Explanation

Shape is the base class.


Rectangle and Circle are subclasses.
Both subclasses define their own area() method.

The same method area() is called for different objects (rect, cir).
Each object executes its own implementation, demonstrating polymorphism.

Sample Output
Area of Rectangle: 50
Area of Circle: 153.93804002589985

This program shows polymorphism, where the same method name (area) behaves differently for
different classes.
Sources

the difference between accessors and mutators

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/22
Difference Between Accessors and Mutators

In object-oriented programming, accessors and mutators are methods used to interact with the data
(attributes) of an object. Accessors allow reading the data, while mutators allow modifying it.

Module 4 Programming in Python …

Aspect Accessor Mutator


A method used to access (read) the value A method used to modify or update the
Definition
of an object's attribute. value of an object's attribute.
Purpose Used to retrieve data from an object. Used to change or set data in an object.
Effect on Data Does not change the object's state. Changes the object's state.
Naming
Usually starts with get (e.g., getName()). Usually starts with set (e.g., setName()).
Convention
getFruitName() returns the name of the
Example setFruitName() changes the fruit name.
fruit.

Example
class Fruit:
def __init__(self, name):
[Link] = name

# Accessor
def getFruitName(self):
return [Link]

# Mutator
def setFruitName(self, name):
[Link] = name

Explanation

getFruitName() → accessor method that returns the fruit name.


setFruitName() → mutator method that updates the fruit name.

Key Point

Accessors read data, while mutators modify data in an object.

Sources

Write a python program to create a 3x3 matrix and computation

Python Program to Create a 3×3 Matrix and Perform Computations

In NumPy, matrices are represented using multidimensional arrays (ndarray). NumPy provides functions
to perform operations like addition, subtraction, multiplication, transpose, and determinant on
matrices.
Module 5 Programming in Python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/22
Module 5 Programming in Python …

Python Program
import numpy as np

# Create a 3x3 matrix


A = [Link]([[1,2,3],
[4,5,6],
[7,8,9]])

print("Matrix A:")
print(A)

# Matrix Transpose
print("\nTranspose of matrix:")
print(A.T)

# Trace of matrix
print("\nTrace of matrix:")
print([Link](A))

# Determinant of matrix
print("\nDeterminant of matrix:")
print([Link](A))

Explanation

[Link]() → creates the 3×3 matrix.


A.T → finds the transpose of the matrix.
[Link](A) → calculates the sum of diagonal elements.

[Link](A) → calculates the determinant of the matrix.

Sample Output
Matrix A:
[[1 2 3]
[4 5 6]
[7 8 9]]

Transpose of matrix:
[[1 4 7]
[2 5 8]
[3 6 9]]

Trace of matrix:
15

Determinant of matrix:
0

This program demonstrates creating a 3×3 matrix and performing basic matrix computations using
NumPy.
Sources

Inheritance in python - Program

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/22
Python Program Demonstrating Inheritance

Inheritance is an object-oriented programming concept where a child class inherits the properties
and methods of a parent class. It helps in code reusability because a new class can use the features of
an existing class.
Module 4 Programming in Python …

Example Program
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def show_details(self):
print("Name:", [Link])
print("Age:", [Link])

# Child class inheriting Person


class Student(Person):
def __init__(self, name, age, rollno):
super().__init__(name, age)
[Link] = rollno

def show_student(self):
print("Roll No:", [Link])

# Create object of child class


s1 = Student("Rahul", 20, 101)

# Access inherited and own methods


s1.show_details()
s1.show_student()

Explanation

Person → Parent (base) class.


Student → Child (derived) class that inherits from Person.

super().__init__(name, age) → calls the constructor of the parent class.


s1 = Student("Rahul",20,101) → creates an object of the child class.
show_details() → inherited method from parent class.

show_student() → method defined in the child class.

Sample Output
Name: Rahul
Age: 20
Roll No: 101

This program shows how a child class inherits attributes and methods from a parent class in
Python.

Sources

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/22
Explain in detail about abstract class in python with an example.

Abstract Class in Python

Abstraction means hiding the complexity and showing only the essential features of an object. In
simple terms, the user knows how to use something, but does not need to know its full internal
implementation.
Module 4 Programming in Python …
An abstract class is a class that contains one or more abstract methods. An abstract method is a
method that generally does not have an implementation, and its implementation is left to the
subclasses.
Module 4 Programming in Python …

Important points about abstract class

An abstract class is a class that contains one or more abstract methods.


Module 4 Programming in Python …
An abstract method usually does not contain implementation; subclasses must provide the
implementation.
Module 4 Programming in Python …
An abstract class cannot be instantiated, so we cannot create objects directly from it.

Module 4 Programming in Python …


In Python, an abstract class is created by deriving from ABC from the abc module.

To define an abstract method, we use the @abstractmethod decorator.


An abstract class can contain both abstract methods and concrete methods.
Module 4 Programming in Python …
An abstract class works as a template for other classes.
Module 4 Programming in Python …
If a derived class does not implement an abstract method, Python throws an error.

Module 4 Programming in Python …

Syntax for abstract class


from abc import ABC

class MyClass(ABC):
pass

Syntax for abstract method


from abc import ABC, abstractmethod

class MyClass(ABC):
@abstractmethod
def mymethod(self):
pass

Example Program

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/22
from abc import ABC, abstractmethod

class Parent(ABC):
def common(self):
print("I am the common of parent")

@abstractmethod
def vary(self):
pass

class Child1(Parent):
def vary(self):
print("I am vary of child1")

class Child2(Parent):
def vary(self):
print("I am vary method of child2")

obj1 = Child1()
[Link]()
[Link]()

obj2 = Child2()
[Link]()
[Link]()

Output
I am the common of parent
I am vary of child1
I am the common of parent
I am vary method of child2

Explanation of the program

Parent is an abstract class because it inherits from ABC.


common() is a concrete method because it has a body and can be used directly by subclasses.

Module 4 Programming in Python …


vary() is an abstract method because it is decorated with @abstractmethod.
Child1 and Child2 are derived classes that provide their own implementation of vary().

Module 4 Programming in Python …


Objects are created only for Child1 and Child2, not for Parent, because abstract classes cannot be
instantiated.

Simple explanation

An abstract class is like a model or blueprint. It tells child classes, “you must implement this method.”
So, the abstract class provides the common structure, and the subclasses provide the actual working
details.

Conclusion

Abstract class in Python is used to achieve abstraction. It helps in defining a common template for
subclasses. By using ABC and @abstractmethod, Python ensures that every subclass properly implements
the required methods.
Sources

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/22
Write Python program to write the data given below to a CSV file (data you can create should 3 or
4)

Python Program to Write Data to a CSV File

CSV (Comma Separated Values) files are used to store tabular data such as names, marks, or
employee records. In Python, the csv module is used to write data into a CSV file.

Example Program
import csv

# Data to write to CSV file


data = [
["ID", "Name", "Age"],
[1, "Rahul", 21],
[2, "Anu", 22],
[3, "Sanu", 20],
[4, "Meera", 23]
]

# Write data to CSV file


with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](data)

print("Data written to CSV file successfully.")

Explanation

import csv → imports the CSV module.

data → list containing rows of data to be written.


open("[Link]","w") → creates a CSV file in write mode.

[Link](file) → creates a writer object.


[Link](data) → writes multiple rows into the CSV file.

Output ([Link] file)


ID,Name,Age
1,Rahul,21
2,Anu,22
3,Sanu,20
4,Meera,23

This program creates a CSV file and writes 3–4 records of data into it.

Define a class Student in Python with attributes to store the roll number, name and marks of
three subjects for each student. Define the following methods:
a. readData() - to assign values to the attributes
b. computeTotal() - to find the total marks

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/22
c. print_details() - to display the attribute values and the total marks
d. Create an object of the class and invoke the methods.

Python Program: Student Class with Required Methods

A class is a blueprint used to create objects. It contains attributes (data members) and methods
(functions) that operate on the data. An object is an instance of a class used to access its attributes and
methods.
Module 4 Programming in Python …

Program
class Student:

# Method to read student data


def readData(self):
[Link] = int(input("Enter Roll Number: "))
[Link] = input("Enter Name: ")
self.m1 = int(input("Enter marks of Subject 1: "))
self.m2 = int(input("Enter marks of Subject 2: "))
self.m3 = int(input("Enter marks of Subject 3: "))

# Method to compute total marks


def computeTotal(self):
[Link] = self.m1 + self.m2 + self.m3

# Method to print details


def print_details(self):
print("\nStudent Details")
print("Roll Number:", [Link])
print("Name:", [Link])
print("Marks:", self.m1, self.m2, self.m3)
print("Total Marks:", [Link])

# Create object of Student class


s1 = Student()

# Invoke methods
[Link]()
[Link]()
s1.print_details()

Explanation

class Student: → defines a class named Student.


readData() → reads and assigns roll number, name, and marks.
computeTotal() → calculates the total marks of three subjects.

print_details() → displays the student details and total marks.


s1 = Student() → creates an object of the class.
[Link](), [Link](), s1.print_details() → invoke the methods using the object.

Sample Output

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/22
Enter Roll Number: 101
Enter Name: Rahul
Enter marks of Subject 1: 80
Enter marks of Subject 2: 75
Enter marks of Subject 3: 90

Student Details
Roll Number: 101
Name: Rahul
Marks: 80 75 90
Total Marks: 245
Sources

Write a python program to input two matrices using numpy ,find addition of those matrices and
display the result

Python Program to Input Two Matrices Using NumPy and Find Their Addition

In NumPy, matrices are represented using arrays (ndarray), and arithmetic operations like addition are
performed element-wise between corresponding elements of arrays.
Module 5 Programming in Python …

Program
import numpy as np

# Input matrices
print("Enter elements of first 2x2 matrix:")
A = [Link]([[int(input()), int(input())],
[int(input()), int(input())]])

print("Enter elements of second 2x2 matrix:")


B = [Link]([[int(input()), int(input())],
[int(input()), int(input())]])

# Matrix addition
C = A + B

# Display matrices and result


print("\nFirst Matrix:")
print(A)

print("\nSecond Matrix:")
print(B)

print("\nAddition of Matrices:")
print(C)

Explanation

import numpy as np → imports the NumPy library.


[Link]() → creates matrices using NumPy arrays.

A + B → performs element-wise addition of the matrices.


The result matrix C contains the sum of corresponding elements.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/22
Sample Output
Enter elements of first 2x2 matrix:
1
2
3
4
Enter elements of second 2x2 matrix:
5
6
7
8

First Matrix:
[[1 2]
[3 4]]

Second Matrix:
[[5 6]
[7 8]]

Addition of Matrices:
[[ 6 8]
[10 12]]

This program inputs two matrices using NumPy, adds them, and displays the resulting matrix.
Sources

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/22

You might also like