0% found this document useful (0 votes)
41 views35 pages

Pip QP

python pip questions and answers

Uploaded by

tkm21cs077
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)
41 views35 pages

Pip QP

python pip questions and answers

Uploaded by

tkm21cs077
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
You are on page 1/ 35

1. Explain type conversion with example.

Ans:

Python defines type conversion functions to directly convert one data type to
another data type. There are two types of Type Conversion in Python:

->Python Implicit Type Conversion:

-Python interpreter automatically converts one data type to another


without any user involvement.

-eg:-

x = 10 => int

y = 10.6 => float

z=x+y

print(z)

print("z is of type:",type(z)) => float

->Python Explicit Type Conversion

- the data type is manually changed by the user as per their


requirement

- there is a risk of data loss

-eg:-

s = "10010" => string

c = int(s)

print (type(c)) => int

e = float(s)

print(type(e)) => float


2. Write a program that accepts the lengths of three sides of a triangle as inputs and

outputs whether or not the triangle is a right triangle

Ans:

print("Enter the sides: ")

z=int(input("The longest side: "));

x=int(input());

y=int(input());

if x**2 + y**2 == z**2:

print("Yes, it is right-angled triangle")

else:

print("No, it is not right-angled triangle")


3. Differentiate between lists and tuples with the help of examples.

Ans:

LIST TUPLE
Lists are mutable Tuples are immutable
The implication of iterations is The implication of iterations is
Time-consuming comparatively faster.

The list is better for performing Tuple data type is appropriate


operations, for accessing the elements
such as insertion and deletion.
Lists consume more memory Tuple consumes less memory
as compared to the list
Lists have several built-in Tuple does not have many built-
methods in methods.

Unexpected changes and errors Because tuples don’t change


are more likely to occur they are far less error-prone

4. Write a Python program to print all palindromes in a line of text.

Ans:
def main():

line = input("Enter a line of text: ")

words = line.split()

palindromes = [word for word in words if word == word[::-1]]

if palindromes:

print("Palindromes found:", ", ".join(palindromes))

else:

print("No palindromes found in the given line of text.")

if __name__ == "__main__":

main()

5. Comment on event driven programming.

Ans:

-Event-driven programming is a powerful paradigm used in Python for building


responsive and scalable applications.

-Python’s event-driven programming model revolves around the concept of an


event loop.

-An event loop continuously monitors events and dispatches them to the
appropriate event handlers.

-Event-driven programming allows the program to efficiently handle multiple


asynchronous tasks concurrently.
-The flow of the program is driven by events such as user actions, system
notifications, or messages from other parts of the program.

6. Write a Python program to draw a hexagon using turtle graphics.

Ans:

import turtle

hexagon_turtle = turtle.Turtle()

hexagon_turtle.speed(1)

for _ in range(6):

hexagon_turtle.forward(100)

hexagon_turtle.right(60)

turtle.done()

7. Give an example for constructor overloading.

Ans:

Constructor overloading refers to defining multiple constructors within a class,


each with a different number or type of parameters.

Eg: class Rectangle:

def __init__(self, width=None, height=None):

if width is not None and height is not None:

self.width = width

self.height = height

elif width is not None:

self.width = width

self.height = width
else:

self.width = 0

self.height = 0

def area(self):

return self.width * self.height

rect1 = Rectangle(5, 10)

print("Area of rect1:", rect1.area())

rect2 = Rectangle(7)

print("Area of rect2:", rect2.area())

rect3 = Rectangle()

print("Area of rect3:", rect3.area())

8. Explain method overriding in Python.

Ans:

Method overriding in Python occurs when a subclass provides a specific


implementation of a method that is already defined in its superclass.

Eg: class Animal:

def make_sound(self):

print("Generic animal sound")

class Dog(Animal):

def make_sound(self):

print("Woof!")

class Cat(Animal):

def make_sound(self):
print("Meow!")

dog = Dog()

cat = Cat()

dog.make_sound()

cat.make_sound()

9. Explain the attributes of an ndarray object.

Ans:

In NumPy, an `ndarray` (n-dimensional array) object is the fundamental data


structure used to represent arrays. It is a highly flexible and efficient container for
homogeneous data. Here are some of the key attributes of an `ndarray` object:

1. shape: This attribute returns a tuple representing the dimensions of the


array. For example, a 2D array with 3 rows and 4 columns would have a
shape of `(3, 4)`.
2. type: This attribute indicates the data type of the elements stored in the
array. NumPy supports various data types such as integers, floats,
booleans, etc. For example, `int64` represents a 64-bit integer.
3. size: This attribute returns the total number of elements in the array. It is
equal to the product of the dimensions specified in the `shape` attribute.
4. ndim: This attribute returns the number of dimensions (or axes) of the
array.
5. itemsize: This attribute returns the size in bytes of each element in the
array.
6. nbytes: This attribute returns the total number of bytes consumed by the
elements of the array. It is equal to `itemsize` times `size`.
7. data: This attribute is a buffer containing the actual elements of the array.
It is rarely used directly.

Eg. import numpy as np


arr = np.array([[1, 2, 3], [4, 5, 6]])

print("Array:", arr)

print("Shape:", arr.shape)

print("Data Type:", arr.dtype)

print("Size:", arr.size)

print("Number of Dimensions:", arr.ndim)

print("Size of Each Element (in bytes):", arr.itemsize)

print("Total Number of Bytes:", arr.nbytes)

Output:

Array: [[1 2 3]

[4 5 6]]

Shape: (2, 3)

Data Type: int64

Size: 6

Number of Dimensions: 2

Size of Each Element (in bytes): 8

Total Number of Bytes: 48

10. Explain the use of flask in web development.

Ans:

Flask is a lightweight web framework for Python that simplifies web development
by providing tools and libraries for building web applications. Here's how Flask is
used in web development:

1. Routing: Flask allows developers to define URL routes and associate them
with specific functions, known as view functions.
2. Template Rendering: Flask supports template engines such as Jinja2, which
allows developers to create dynamic HTML templates.
3. Request Handling: Flask provides convenient ways to access and process
incoming HTTP requests.
4. Response Generation: Flask enables developers to generate HTTP
responses dynamically.
5. Middleware: Flask allows developers to plug in middleware components to
handle cross-cutting concerns such as authentication, logging, or error
handling.
6. Extension Ecosystem: Flask has a rich ecosystem of extensions that provide
additional functionality for common tasks such as user authentication,
database integration, caching, and more.

11 A)

Discuss the steps involved in the waterfall model of software development

process with the help of a neat diagram.

Ans:

When used for a software development process, the waterfall methodology has seven
stages:

1. Requirements. Potential requirements, deadlines and guidelines for the


project are analyzed and placed into a formal requirements document, also
called a functional specification. This stage of development defines and plans
the project without mentioning specific processes.

2. Analysis. The system specifications are analyzed to generate product


models and to guide production. This is also when financial and technical
resources are audited for feasibility.

3. Design. A design specification document is created to outline technical


design requirements, such as the programming language, hardware, data
sources, architecture and services.
4. Coding and implementation. The source code is developed using the
models, logic and requirement specifications designated in the prior phases.
Typically, the system is coded in smaller components, or units, before being
put together.

5. Testing. This is when quality assurance, unit, system and beta tests identify
issues that must be resolved. This may cause a forced repeat of the coding
stage for debugging. If the system passes integration and testing, the
waterfall continues forward.

6. Operation and deployment. The product or application is deemed fully


functional and is deployed to a live environment.

7. Maintenance. Corrective, adaptive and perfective maintenance is carried out


indefinitely to improve, update and enhance the product and its functionality.
This could include releasing patch updates and new versions.
11 B)

Write a Python program to print all numbers between 100 and 1000 whose sum

of digits is divisible by 9.

Ans:

def main():

numbers = []

for num in range(100, 1001):

digit_sum = 0

for digit in str(num):

digit_sum += int(digit)

if digit_sum % 9 == 0:

numbers.append(num)

print("Numbers between 100 and 1000 whose sum of digits is

divisible by 9:")

print(numbers)

if __name__ == "__main__":

main()

12 A)

Illustrate the use of range() in Python.

Ans:
The range() function returns a sequence of numbers.

Starting from 0 by default, and increments by 1 (by default), and stops


before a specified number.

Syntax : range(start, stop, step)

start Optional. An integer number specifying at which position to start.

Default is 0

stop Required. An integer number specifying at which position to stop (not


included).

step Optional. An integer number specifying the incrementation. Default is 1

x = range(3, 6)

for n in x:

print(n) => 3 4 5

x = range(3, 20, 2)

for n in x:

print(n) => 3 5 7 9 11 13 15 17 19

12 B)

Write a Python program to print all prime factors of a given number.

Ans:

def main():
# Input number from user
number = int(input("Enter a number: "))
factors = []
# Find and store factors of 2
while number % 2 == 0:
factors.append(2)
number //= 2

# Find and store factors of odd numbers from 3 onwards


for i in range(3, number + 1, 2):
while number % i == 0:
factors.append(i)
number //= i

# Output the list of prime factors


print("The prime factors are:", factors)

if __name__ == "__main__":
main()

13 A)

Write a Python program to compute the sum of the series

(1 - x^2/2! + x^4/4! - x^6/6!+..........n terms).

Ans:

import math

def main():

n=int(input())

x=9

sum = 1

term = 1

y=2
for i in range(1, n):

factorial = 1

for j in range(1, y + 1):

factorial = factorial * j

term *= (-1)

m = term * (x ** y) / factorial

sum += m

y += 2

print(f"{sum:.4f}")

if __name__ == "__main__":

main()

13 B)

Illustrate the use of any 4 dictionary methods.

Ans:

i. get( ):
- Returns the value for a specified key in the dictionary.
- If the key is not found, it returns a default value (None by default).

ii. keys( ):
- Returns a view object that displays a list of all the keys in the dictionary.

iii. pop( ):
- Removes the item with the specified key from the dictionary

and returns its value.

iv. update( ):
- Updates the dictionary with the elements from another dictionary
or iterable object.

v. values( ):
- Returns a view object that displays a list of all the values

in the dictionary.

vi. items( ):
- Returns a view object that displays a list of tuples containing

the key-value pairs in the dictionary.

Example:
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict.get("name")) # Output: John
print(my_dict.get("salary")) # Output: None
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
removed_value = my_dict.pop("age")
print(removed_value) # Output: 30
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
update_dict = {"age": 30, "salary": 50000}
my_dict.update(update_dict)
print(my_dict) # Output: {'name': 'John', 'city': 'New York', 'age': 30, 'salary':
50000}
print(my_dict.values()) # Output: dict_values(['John', 'New York',30,50000])
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('city', 'New York'),
('age', 30),(‘salary’,50000)])

14 A)

Write a python program to convert a decimal number to its binary equivalent.

Ans:

if num >= 1:

DecimalToBinary(num // 2)

print(num % 2, end = ' ')


if __name__ == '__main__':

dec = int(input("Enter the value: "))

DecimalToBinary(dec)

14 B)

Write a python program to read a text file and store the count of occurrences of
each character in a dictionary

Ans:

def main():
file_path = 'file.txt'

char_count = {}

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


text = file.read()

for char in text:


if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1

for char, count in char_count.items():


print(f"'{char}': {count}")

if __name__ == "__main__":
main()
15 A)

Write a Python program to convert a color image to a grayscale image.

Ans:

def grayscale(image):

for y in range(image.getHeight):
for x in rangeimage.get Width):
(r, g, b) = image.getPixel(x, y)
r = intr * 0.299)
g = int(g * 0.587)
b = int(b* 0.114)
lum = r +g+b
image.setPixel(x, y, (lum, lum, lum))

15 B)

Explain the attributes and methods of Turtle object.

Ans:

Turtle Graphics

The sheet of paper is a window on a display screen, and the turtle is an icon, such as an
arrowhead. At any given moment in time, the turtle is located at a specific position in
the window. This position is specified with (x, y) coordinates. The coordinate system for
Turtle graphics is the standard Cartesian system, with the origin (0, 0) at the center of a
window. The turtle's initial position is the origin which is also called the home. An
equally important attribute of a turtle is its heading, or the direction in which it currently
faces. The turtle's initial heading is 0 degrees, or due east on its map. The degrees of the
heading increase as it turns to the left, so 90 degrees is due north.

Turtle Attributes:

Heading -> Specified in degrees, the heading or direction increases in value as the turtle
turns to the left, or counterclockwise. Conversely, a negative quantity of degrees
indicates a right, or clockwise, turn. The turtle is initially facing east, or 0 degrees. North
is 90 degrees

Color -> Initially black, the color can be changed to any of more than 16 million other
colors.

Width -> This is the width of the line drawn when the turtle moves. The initial width is 1
pixel.

Down -> This attribute, which can be either true or false, controls whether the turtle's
pen is up or down. When true (that is, when the pen is down), the turtle draws a line
when it moves. When false (that is, when the pen is up), the turtle can move without
drawing a line

Turtle Methods :-

t = Turtle() -> Creates a new Turtle object and opens its window.

t.home () -> Moves t to the center of the window and then points t east.

t.up() -> Raises t's pen from the drawing surface.

t.down() -> Lowers t's pen to the drawing surface.

t.setheading (degrees) ->Points t in the indicated direction, which is specified in


degrees. East is 0 degrees, north is 90 degrees, west is 180 degrees, and south is 270
degrees.

t.left(degrees) t.right(degrees) -> Rotates t to the left or the right by the specified
degrees.

t.goto(x, y) -> Moves t to the specified position.

t.forward(distance) -> Moves t the specified distance in the current direction.


16. A)

Write Python GUI program to input two strings and output a concatenated string
when a button is pressed.

Ans:

import tkinter as tk

def concatenate_strings():

string1 = entry1.get()

string2 = entry2.get()

concatenated_string = string1 + " " + string2

result_label.config(text="Concatenated String: " + concatenated_string)

root = tk.Tk()

root.title("String Concatenation")

label1 = tk.Label(root, text="Enter String 1:")

label1.grid(row=0, column=0, padx=5, pady=5)

entry1 = tk.Entry(root)

entry1.grid(row=0, column=1, padx=5, pady=5)

label2 = tk.Label(root, text="Enter String 2:")

label2.grid(row=1, column=0, padx=5, pady=5)

entry2 = tk.Entry(root)

entry2.grid(row=1, column=1, padx=5, pady=5)

concat_button = tk.Button(root, text="Concatenate",


command=concatenate_strings)

concat_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

result_label = tk.Label(root, text="")

result_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)


root.mainloop()

16. b)

Discuss on the types of window components and their functions.


Ans:

In GUI programming, window components (also known as widgets or controls)


are graphical elements that allow users to interact with the application. Here are
some common types of window components and their functions:

1. Labels: Labels are used to display text or descriptive information to the


user. They are typically non-editable and provide instructions or
descriptions for other components.
2. Buttons: Buttons are interactive components that users can click on to
perform actions or trigger events. They are commonly used for actions like
submitting forms, navigating between screens, or executing commands.
3. Text Input Fields: Text input fields allow users to enter text or numerical
data. They are used for accepting user input, such as entering usernames,
passwords, search queries, or other information.
4. Checkboxes: Checkboxes are used to present users with binary choices.
They are commonly used for enabling/disabling options, selecting multiple
items from a list, or indicating agreement to terms and conditions.
5. Radio Buttons: Radio buttons are used to present users with a list of
mutually exclusive options. Users can select only one option from the list.
They are commonly used when users need to choose one option from a
set of options.
6. Dropdown Menus: Dropdown menus (also known as combo boxes or
dropdown lists) allow users to select an option from a predefined list of
choices. They conserve space by hiding the list of options until the user
clicks on the dropdown arrow.
7. Sliders: Sliders (also known as scroll bars or trackbars) allow users to select
a value from a continuous range by dragging a handle along a track. They
are commonly used for selecting values like volume, brightness, or zoom
level.
8. Progress Bars: Progress bars provide visual feedback to users about the
progress of an ongoing task. They indicate the percentage completion of a
task and are commonly used for tasks like file downloads, software
installations, or data processing.
9. Text Areas: Text areas are multi-line input fields that allow users to enter
longer blocks of text. They are used when users need to provide more
extensive input, such as composing emails, writing messages, or entering
comments.
10. Images: Images can be displayed within a GUI to provide visual content or
enhance the user interface. They can be static images or dynamically
updated based on user interactions or application state.

17. a)

Illustrate the use of abstract classes in Python.

Ans:

Abstract classes in Python are classes that cannot be instantiated on their own
and are meant to be subclassed. They typically contain one or more abstract
methods, which are methods without implementations. Abstract classes serve as
templates for concrete subclasses to implement their own versions of the
abstract methods. Here's an illustration of how abstract classes are used in
Python:

Eg. from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod

def area(self):

pass

@abstractmethod

def perimeter(self):
Pass

class Rectangle(Shape):

def __init__(self, width, height):

self.width = width

self.height = height

def area(self):

return self.width * self.height

def perimeter(self):

return 2 * (self.width + self.height)

class Circle(Shape):

def __init__(self, radius):

self.radius = radius

def area(self):

return 3.14 * self.radius ** 2

def perimeter(self):

return 2 * 3.14 * self.radius

try:

s = Shape() # This will raise an error

except Exception as e:

print("Error:", e)

rectangle = Rectangle(5, 4)

circle = Circle(3)

print("Area of Rectangle:", rectangle.area())

print("Perimeter of Rectangle:", rectangle.perimeter())


print("Area of Circle:", circle.area())

print("Circumference of Circle:", circle.perimeter())

17. b)

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:

• readData()- to assign values to the attributes.


• computeTotal() – to find the total marks.
• print_details() - to display the attribute values and the total marks.

Create an object of the class and invoke the methods.

Ans:

class Student:

def __init__(self):

self.roll_number = None

self.name = None

self.marks = [0, 0, 0] # Assuming three subjects

def read_data(self):

self.roll_number = input("Enter Roll Number: ")

self.name = input("Enter Name: ")

for i in range(3):

self.marks[i] = float(input(f"Enter Marks for Subject {i+1}: "))

def compute_total(self):

return sum(self.marks)

def print_details(self):
print("Roll Number:", self.roll_number)

print("Name:", self.name)

for i in range(3):

print(f"Marks for Subject {i+1}: {self.marks[i]}")

print("Total Marks:", self.compute_total())

student1 = Student()

student1.read_data()

student1.print_details()

18. a)

Explain, with the help of suitable examples, the different types of inheritance.

Ans:

Inheritance is a fundamental concept in object-oriented programming (OOP) that


allows a new class (subclass) to inherit attributes and methods from an existing
class (superclass). Let's discuss each type with suitable examples:

1. Single Inheritance

Single inheritance occurs when a subclass inherits from only one


superclass. In this type of inheritance, the subclass inherits the attributes
and methods of the superclass.
Eg. class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def bark(self):

print("Dog barks")

dog = Dog()

dog.speak()

dog.bark()

2. Multiple Inheritance

Multiple inheritance occurs when a subclass inherits from more than one
superclass. In this type of inheritance, the subclass inherits attributes and
methods from all the superclasses.
Eg. class Flyable:

def fly(self):

print("Can fly")

class Swimmable:

def swim(self):

print("Can swim")

class Duck(Flyable, Swimmable):

pass

duck = Duck()

duck.fly()

duck.swim()

3. Multilevel Inheritance

Multilevel inheritance occurs when a subclass inherits from another


subclass. In this type of inheritance, a chain of inheritance is formed, where
each subclass inherits attributes and methods from its superclass.
Eg. class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def bark(self):

print("Dog barks")

class Labrador(Dog):

def color(self):

print("Labrador is brown")

labrador = Labrador()

labrador.speak() # Output: Animal speaks

labrador.bark() # Output: Dog barks

labrador.color() # Output: Labrador is brown

4. Hierarchical Inheritance

Hierarchical inheritance occurs when multiple subclasses inherit from the


same superclass. In this type of inheritance, a single superclass is inherited
by multiple subclasses.
Eg. class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def bark(self):

print("Dog barks")

class Cat(Animal):

def meow(self):

print("Cat meows")

dog = Dog()

cat = Cat()

dog.speak() # Output: Animal speaks

cat.speak() # Output: Animal speaks

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. It


can involve any combination of single, multiple, multilevel, or hierarchical
inheritance.
Eg. class Animal:

def speak(self):

print("Animal speaks")

class Flyable:

def fly(self):

print("Can fly")

class Bird(Animal, Flyable):

Pass

bird = Bird()

bird.speak()

bird.fly()

18. b)

Write a Python program to demonstrate the use of try, except and finally blocks.

Ans:

1. try: The `try` block is used to enclose the code that might raise an
exception. When an exception occurs within the `try` block, Python
searches for an associated `except` block to handle the exception.
2. except: The `except` block is used to handle exceptions that occur within
the corresponding `try` block. It allows you to specify how the program
should respond to different types of exceptions. If an exception occurs in
the `try` block, Python looks for a matching `except` block. If a match is
found, the code inside the `except` block is executed.
3. finally: The `finally` block is always executed regardless of whether an
exception occurs or not. It is typically used to perform cleanup actions,
such as closing files or releasing resources. The `finally` block is executed
even if there is an unhandled exception or a return statement within the
`try` or `except` block.

Eg. def divide(x, y):

try:

result = x / y

except ZeroDivisionError:

print("Error: Division by zero!")


else:

print("Result:", result)

finally:

print("Finally block executed")

19. a)

Consider a CSV file ‘weather.csv’ with the following columns (date, temperature,
humidity, windSpeed, precipitationType, place, weather {Rainy, Cloudy, Sunny}).
Write commands to do the following using Pandas library.

1. Print first 10 rows of weather data.


2. Find the maximum and minimum temperature.
3. List the places with temperature less than 28oC.
4. List the places with weather = “Cloudy”.
5. Sort and display each weather and its frequency.
6. Create a bar plot to visualize temperature of each day.

Ans:

import pandas as pd

weather_data = pd.read_csv('weather.csv')

print("First 10 rows of weather data:")

print(weather_data.head(10))

max_temp = weather_data['temperature'].max()

min_temp = weather_data['temperature'].min()

print("\nMaximum Temperature:", max_temp)

print("Minimum Temperature:", min_temp)

places_less_than_28 = weather_data[weather_data['temperature'] <


28]['place'].unique()

print("\nPlaces with temperature less than 28°C:")

print(places_less_than_28)

cloudy_places = weather_data[weather_data['weather'] ==
'Cloudy']['place'].unique()

print("\nPlaces with weather = 'Cloudy':")

print(cloudy_places)

weather_frequency = weather_data['weather'].value_counts().sort_index()

print("\nWeather and its frequency:")

print(weather_frequency)

weather_data.plot(kind='bar', x='date', y='temperature', figsize=(10, 6),


title='Temperature of Each Day')

plt.xlabel('Date')

plt.ylabel('Temperature (°C)')
plt.show()

19. b)

Explain the different ways by which numpy arrays are created.

Ans:

NumPy offers various methods to create arrays, providing flexibility and


convenience in array creation. Here are the different ways to create NumPy
arrays:

1. Using Python Lists or Tuples: You can create a NumPy array from a Python
list or tuple using the `np.array()` function.

Eg. import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])

arr2 = np.array((6, 7, 8, 9, 10))

2. Using `np.arange()`: This function creates an array with evenly spaced


values within a specified range.

Eg. arr3 = np.arange(1, 11)

3. Using `np.linspace()`: This function creates an array with evenly spaced


values over a specified interval.

Eg. arr4 = np.linspace(0, 1, 5)

4. Using `np.zeros()` and `np.ones()`: These functions create arrays filled with
zeros or ones, respectively.

Eg. zeros_arr = np.zeros((2, 3))

ones_arr = np.ones((3, 2)) # Creates a 3x2 array filled with ones

5. Using `np.eye()`: This function creates an identity matrix (a square matrix


with ones on the diagonal and zeros elsewhere).

Eg. identity_matrix = np.eye(3) # Creates a 3x3 identity matrix


6. Using `np.random.rand()` and `np.random.randn()`: These functions create
arrays with random values from a uniform or normal distribution,
respectively.

Eg. random_arr = np.random.rand(2, 2)

normal_random_arr = np.random.randn(3)

7. Using `np.diag()`: This function creates a diagonal array from a given array
or list of values.

Eg. diagonal_arr = np.diag([1, 2, 3, 4])

8. Using Custom Functions: You can create arrays using custom functions like
`np.fromfunction()`, which constructs arrays by executing a function over
each coordinate.

Eg. def my_func(i, j):

return 3 * i + j

custom_arr = np.fromfunction(my_func, (3, 3))

20. a)

Write Python program to write the data given below to a CSV file.

Sl No. Title Author Available Count

1 The Great Gasby F. Scott Fitzgerald Y 20

2 Pride and Prejudice Jane Austen Y 15

3 The Time Machine H.G. Wells N 0


Ans:

import csv

data = [
['Sl No.', 'Title', 'Author', 'Available', 'Count'],

[1, 'The Great Gatsby', 'F. Scott Fitzgerald', 'Y', 20],

[2, 'Pride and Prejudice', 'Jane Austen', 'Y', 15],

[3, 'The Time Machine', 'H.G. Wells', 'N', 0]

filename = 'books.csv'

with open(filename, mode='w', newline='') as file:

writer = csv.writer(file)

writer.writerows(data)

print("Data has been written to", filename)

20. b)

Write a Python program to input two matrices and perform the following
operations using numpy and display the results:

1. Add the matrices.


2. Subtract the matrices.
3. Multiply the matrices.
4. Find transpose of the matrices

Ans:

import numpy as np

def input_matrix(rows, cols):

matrix = []

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

for i in range(rows):

row = list(map(int, input().split()))


matrix.append(row)

return np.array(matrix)

rows, cols = map(int, input("Enter dimensions (rows and columns) of the matrices:
").split())

print("\nEnter elements of the first matrix:")

matrix1 = input_matrix(rows, cols)

print("\nEnter elements of the second matrix:")

matrix2 = input_matrix(rows, cols)

addition_result = np.add(matrix1, matrix2)

subtraction_result = np.subtract(matrix1, matrix2)

multiplication_result = np.dot(matrix1, matrix2)

transpose_matrix1 = np.transpose(matrix1)

transpose_matrix2 = np.transpose(matrix2)

print("\nResults:")

print("1. Addition of matrices:")

print(addition_result)

print("\n2. Subtraction of matrices:")

print(subtraction_result)

print("\n3. Multiplication of matrices:")

print(multiplication_result)

print("\n4. Transpose of the first matrix:")

print(transpose_matrix1)

print("\n5. Transpose of the second matrix:")

print(transpose_matrix2)

You might also like