Python Papper

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

Paper-1 [6034-505]

Ques-1 Attempt any eight of the following.


1) What are special operators in python?
 Special operators in Python are operators that provide additional functionality
beyond the standard arithmetic and logical operators in Python.
 Some of the special operators in Python include:
1. Identity operators: `is` and `is not` are used to compare the memory
locations of two objects.
2. Membership operators: `in` and `not in` are used to check if a value is
present in a sequence (like a list, tuple, string, etc.).
3. Assignment operators: `=`, `+=`, `-=` etc. are used to assign values to
variables and perform operations in a single step.
4. Bitwise operators: `&`, `|`, `^`, `~`, `<<`, `>>` are used to perform bitwise
operations on integers.

2) Difference between Python list and NumPy array.


 Python list and NumPy array are both used to store collections of elements, but they
have some key differences:
 1. Data Types:
 Python lists can store elements of different data types (integers, strings, etc.) in the same
list.
 NumPy arrays are homogeneous, meaning they can only store elements of the same
data type. This allows for more efficient storage and operations on the array.
 2. Performance:
 NumPy arrays are implemented in C, which makes them faster for computations
compared to Python lists which are interpreted.
 3. Functionality:
 NumPy arrays provide a wide range of mathematical functions and operations that can
be applied to the entire array without the need for explicit loops.
 NumPy arrays support broadcasting, which allows operations on arrays of different
shapes.
 4. Memory Usage:
 NumPy arrays consume less memory compared to Python lists, especially for large
datasets, because of their homogeneous data type.
3) State any four-time module.
 The `time` module in Python provides various time-related functions.
 1. time(): This function returns the current time in seconds since the epoch as a floating-
point number. It is often used for measuring the elapsed time in a program.
 2. ctime(): The `ctime()` function converts a time in seconds since the epoch to a string
representing the local time.
 3.sleep(): The `sleep()` function suspends the execution of the current thread for a
specified number of seconds. It is often used for introducing delays in a program.
 4. gmtime(): The `gmtime()` function converts a time in seconds since the epoch to a
struct time object in UTC (Coordinated Universal Time).

4) What is class variable?


 A class variable in Python is a variable that is shared by all instances (objects) of a class.
 It is defined within a class but outside of any class methods.
 Class variables are accessed using the class name rather than through instances of the
class.
 Here is an example of defining and using a class variable in Python:
 ```python
 class MyClass:
 class_variable = 10 # This is a class variable

 def __init__(self, instance_variable):
 self.instance_variable = instance_variable # This is an instance variable

 # Accessing the class variable using the class name
 print(MyClass.class_variable) # Output: 10

 # Creating instances of the class
 obj1 = MyClass(20)

 # Accessing the class variable through an instance
 print(obj1.class_variable) # Output: 10
 ```
 In the example above, `class_variable` is a class variable that is shared among all
instances of the `MyClass` class.
 It is accessed using the class name `MyClass`. Instance variables, on the other hand, are
unique to each instance of the class and are accessed using the `self` keyword within
class methods.

5) List out Geometry management methods.


 In Python GUI programming, geometry management methods help developers design
user interfaces by positioning and arranging widgets within windows or containers in a
structured manner.
 1. Pack Geometry Manager: In Tkinter, the `pack()` method is used to organize widgets
in blocks before placing them in the parent widget. Widgets are packed either
horizontally or vertically.
 2. Grid Geometry Manager: The `grid()` method in Tkinter is used to arrange widgets in
a grid-like structure with rows and columns. Widgets are placed in specific rows and
columns of the parent widget.
 3. Place Geometry Manager: The `place()` method in Tkinter allows you to specify the
exact coordinates (x, y) for placing a widget within its parent widget. This method gives
you precise control over the placement of widgets.

6) Define term Bind Method.


 The term "bind method" refers to a mechanism that allows you to associate an event
with a callback function or method.
 When the specified event occurs on a widget, the associated callback function is
executed.
 In Tkinter, a popular GUI toolkit for Python, the `bind()` method is used to bind events to
callback functions.
 The general syntax for the `bind()` method in Tkinter is:
 ```python
 widget.bind(event, callback)
 ```
 - `widget`: The widget on which the event is being bound.
 - `event`: The event (such as a button click, key press, mouse movement, etc.) that
triggers the callback function.
 - `callback`: The function or method that is called when the specified event occurs.

7) What is Sea born?


 Sea born simplifies the process of creating complex visualizations by providing default
themes and color palettes, as well as functions for easily customizing plot aesthetics.
 It also offers support for grouping data by categories and visualizing relationships
between variables.
 Seaborn provides a variety of functions for creating visually appealing plots, including:
 1. Histograms
 2. Bar plots
 3. Scatter plots
 4. Box plots
 5. Violin plots
 6. Heatmaps
 7. Pair plots
 8. Facet grids
8) Write any two common exceptions in Python.
 Two common exceptions in Python are:
 1. IndexError: Raised when trying to access an index that is out of range in a list or
sequence.
 2. KeyError: Raised when trying to access a key that does not exist in a dictionary.

9) What are the advantages of pandas.


 Pandas is a popular Python library for data manipulation and analysis.
 1. Data Structures: Pandas provides powerful data structures like Series and DataFrame
that make it easy to work with structured data.
 2. Data Analysis: Pandas simplifies data analysis tasks by providing tools for grouping,
aggregating, and analyzing data efficiently.
 3. Performance: Pandas is optimized for performance, making it suitable for handling
large datasets efficiently.
 4. Flexibility: Pandas offers a wide range of functions and methods for data manipulation,
giving users flexibility in how they analyze and process data.

10) How to create class and object in Python?


 In Python, you can create a class using the class keyword, and then instantiate objects
from that class.
 To create a class and object in Python, you can follow these steps:

 class MyClass:
 def __init__(self, x, y):
 self.x = x
 self.y = y

 def my_method(self):
 return self.x + self.y

 # Creating an object of MyClass
 obj = MyClass(3, 5)
 # Accessing attributes and methods of the object
 print(obj.x) # Output: 3
 print(obj.y) # Output: 5
 print(obj.my_method()) # Output: 8

Q2) Attempt any four of the following.


1) a) Explain math and Cmath module in detail.
 Math module in Python:
 The math module in Python provides a set of mathematical functions to perform
mathematical operations. It includes functions for basic arithmetic operations,
trigonometry, logarithms, exponentiation, and more. Some commonly used functions in
the math module include `math.sqrt()` for square root, `math.sin()` for sine function,
`math.cos()` for cosine function, and `math.exp()` for exponential function.
 Example:
 ```python
 import math

 print(math.sqrt(16)) # Output: 4.0
 print(math.sin(math.pi/2)) # Output: 1.0
 ```
 Cmath module in Python:
 The cmath module in Python is an extension of the math module that provides support
for complex numbers. It includes functions to perform mathematical operations on
complex numbers such as addition, subtraction, multiplication, division, exponentiation,
logarithms, trigonometric functions, and more. Some commonly used functions in the
cmath module include `cmath.sqrt()` for square root of a complex number, `cmath.exp()`
for exponential function of a complex number, and `cmath.phase()` for phase angle of a
complex number.

 Example:
 ```python
 import cmath

 z1 = 1 + 2j
 z2 = 3 + 4j

 print(cmath.sqrt(z1)) # Output: (1.272019649514069+0.7861513777574233j)
 print(cmath.exp(z2)) # Output: (-13.128783081462158-15.200784463067954j)
 ```

2) b) Explain different data types in Python.


 Python is a dynamically typed language, which means that you don't have to explicitly
declare the data type of a variable. Python automatically determines the data type based
on the value assigned to the variable. Here are some common data types in Python:
 1. Integer (int): Represents whole numbers without any decimal point. Example: 5, -10,
1000
 2. Float (float): Represents numbers with decimal points. Example: 3.14, -0.5, 2.0
 3. String (str): Represents a sequence of characters enclosed in single quotes (' '), double
quotes (" "), or triple quotes (''' '''). Example: "Hello", 'Python', '''Multi-line string'''
 4. Boolean (bool): Represents a Boolean value which can be either True or False.
Example: True, False
 5. List: Represents an ordered collection of items enclosed in square brackets [ ]. Lists
can contain elements of different data types. Example: [1, 2, 3], ['apple', 'banana',
'cherry']
 6. Tuple: Represents an ordered collection of items enclosed in parentheses ( ). Tuples
are immutable, meaning their elements cannot be changed. Example: (1, 2, 3), ('a', 'b',
'c')
 7. Dictionary (dict): Represents a collection of key-value pairs enclosed in curly braces { }.
Each key-value pair is separated by a colon (:). Example: {'name': 'Alice', 'age': 30}
 8. Set: Represents an unordered collection of unique elements enclosed in curly braces
{ }. Sets do not allow duplicate elements. Example: {1, 2, 3}
 9. NoneType (None): Represents a null value in Python. It is used to define a variable
with no value assigned to it. Example: None
 10. Complex (complex): Represents a complex number with a real and imaginary part.
Complex numbers are represented as <real_part> + <imaginary_part>j. Example: 3 + 4j
 These are some of the common data types in Python. Understanding data types is
essential for effectively working with variables and performing operations on them.

3) c) Explain inheritance in brief with syntax.


 Inheritance is a fundamental concept in object-oriented programming that allows a new
class (derived class or child class) to inherit attributes and methods from an existing class
(base class or parent class). This helps in reusing code and creating a hierarchy of classes.
 Syntax for defining a class with inheritance in Python:
 ```python
 class BaseClass:
 # Base class attributes and methods

 class DerivedClass(BaseClass):
 # Derived class attributes and methods
 ```
 In the above syntax:
 - `BaseClass` is the parent class or superclass from which `DerivedClass` will inherit.
 - `DerivedClass` is the child class or subclass that inherits attributes and methods from
`BaseClass`.
 Example of inheritance in Python:
 ```python
 class Animal:
 def __init__(self, name):
 self.name = name

 def speak(self):
 print(f"{self.name} makes a sound")

 class Dog(Animal):
 def __init__(self, name, breed):
 super().__init__(name)
 self.breed = breed

 def speak(self):
 print(f"{self.name} barks")

 # Creating objects of the derived class
 my_dog = Dog("Buddy", "Golden Retriever")
 my_dog.speak() # Output: Buddy barks
 ```
 In this example:
 - `Animal` is the base class with attributes and methods common to all animals.
 - `Dog` is the derived class that inherits from `Animal` and adds specific attributes and
methods for dogs.
 - The `speak()` method is overridden in the `Dog` class to provide a specific behavior for
dogs.
 Through inheritance, the `Dog` class inherits the `name` attribute and `speak()` method
from the `Animal` class, allowing code reuse and creating a hierarchy between classes.

4) d) Explain various types of exceptional handling in Python.


 Exception handling in Python allows you to handle errors and unexpected situations that
may occur during program execution. There are several types of exception handling
mechanisms in Python:
 1. **try-except block**: The `try-except` block is used to catch and handle exceptions
that occur within a block of code. If an exception is raised within the `try` block, the
corresponding `except` block is executed.
 ```python
 try:
 # Code that may raise an exception
 except SomeException as e:
 # Handle the exception
 ```
 2. **try-except-else block**: The `try-except-else` block is used when you want to
execute some code only if no exceptions are raised in the `try` block.
 ```python
 try:
 # Code that may raise an exception
 except SomeException as e:
 # Handle the exception
 else:
 # Code to execute if no exception is raised
 ```
 3. **try-except-finally block**: The `try-except-finally` block is used to ensure that some
code is always executed, regardless of whether an exception is raised or not. The `finally`
block is commonly used for cleanup operations.
 ```python
 try:
 # Code that may raise an exception
 except SomeException as e:
 # Handle the exception
 finally:
 # Code that always executes
 ```
 4. **Multiple except blocks**: You can have multiple `except` blocks to handle different
types of exceptions separately.

 ```python
 try:
 # Code that may raise different exceptions
 except ValueError as e:
 # Handle ValueError
 except TypeError as e:
 # Handle TypeError
 ```
 5. **Raising exceptions**: You can raise exceptions explicitly using the `raise` statement
to indicate that an error has occurred.
 ```python
 if condition:
 raise SomeException("Error message")
 ```
 6. **Custom exceptions**: You can create custom exception classes by inheriting from
the `Exception` class. This allows you to define your own types of exceptions for specific
situations.
 ```python
 class CustomException(Exception):
 pass
 # Raise custom exception
 raise CustomException("Custom error message")
 ```
 By using these exception handling mechanisms effectively, you can write more robust
and fault-tolerant Python programs that gracefully handle errors and unexpected
situations.

5) e) Explain principle of Keras.


 Keras is a high-level neural networks API written in Python that allows for easy and fast
experimentation with deep learning models. It is designed to be user-friendly, modular,
and extensible, making it popular among both beginners and experts in the field of
machine learning.
 The principle of Keras can be summarized as follows:
 1. **User-friendly interface**: Keras provides a simple and intuitive interface for building
neural networks. It allows users to quickly define and train deep learning models with
just a few lines of code, abstracting away the complexities of lower-level operations.
 2. **Modularity**: Keras follows a modular design where neural networks are built as a
sequence of interconnected layers. Users can easily add, remove, or modify layers to
create different architectures for their models. This modular approach makes it easy to
experiment with various network structures.
 3. **Extensibility**: Keras is built to be highly extensible, allowing users to customize
and extend its functionalities. Users can create custom layers, loss functions, metrics,
and callbacks to tailor the deep learning models to their specific requirements.
 4. **Compatibility**: Keras is designed to be compatible with multiple deep learning
frameworks such as TensorFlow, Theano, and Microsoft Cognitive Toolkit (CNTK). This
allows users to seamlessly switch between backend engines without changing their
code, providing flexibility and interoperability.
 5. **Ease of experimentation**: Keras promotes a rapid prototyping workflow, enabling
users to quickly build and test different neural network architectures. It provides easy-to-
use APIs for training models, evaluating performance, and visualizing results, facilitating
the experimentation process.
 6. **Performance optimization**: While prioritizing ease of use, Keras also focuses on
performance optimization. It leverages the computational capabilities of underlying
frameworks like TensorFlow to efficiently train deep learning models on GPUs and TPUs,
accelerating the training process.

Que: 03) Attempt any four of the following:


1) a) What are built in dictionary functions in Python with example.
 Python provides several built-in dictionary functions that allow you to perform various
operations on dictionaries efficiently. Here are some commonly used built-in dictionary
functions in Python along with examples:
 1. `len()`: Returns the number of key-value pairs in the dictionary.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 print(len(my_dict)) # Output: 3
 ```
 2. `clear()`: Removes all key-value pairs from the dictionary.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 my_dict.clear()
 print(my_dict) # Output: {}
 ```
 3. `keys()`: Returns a view object that displays a list of all the keys in the dictionary.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 print(my_dict.keys()) # Output: dict_keys(['a', 'b', 'c'])
 ```
 4. `values()`: Returns a view object that displays a list of all the values in the dictionary.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 print(my_dict.values()) # Output: dict_values([1, 2, 3])
 ```
 5. `items()`: Returns a view object that displays a list of key-value pairs in the dictionary
as tuples.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 print(my_dict.items()) # Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
 ```
 6. `get()`: Returns the value associated with a specified key. If the key is not found, it
returns a default value (None by default).
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 print(my_dict.get('a')) # Output: 1
 print(my_dict.get('d', 'Key not found')) # Output: 'Key not found'
 ```
 7. `pop()`: Removes the key-value pair with the specified key and returns the
corresponding value.
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 value = my_dict.pop('b')
 print(value) # Output: 2
 print(my_dict) # Output: {'a': 1, 'c': 3}
 ```
 These built-in dictionary functions provide a convenient way to manipulate and extract
information from dictionaries in Python.

2) b) Explain features of pandas in Python.


 Pandas is a powerful and popular open-source data manipulation and analysis library in
Python. It provides easy-to-use data structures and tools for working with structured
data, making it an essential tool for data scientists, analysts, and developers. Here are
some key features of pandas:
 1. **DataFrame**: The DataFrame is the primary data structure in pandas, representing
a two-dimensional, size-mutable, and labeled data structure with columns of potentially
different types. It is similar to a spreadsheet or SQL table, making it easy to store and
manipulate data efficiently.
 2. **Series**: A Series is a one-dimensional labeled array capable of holding any data
type. It is a building block of DataFrames and provides a powerful way to work with
individual columns or rows of data.
 3. **Data Manipulation**: Pandas provides a wide range of functions and methods for
data manipulation, including filtering, sorting, grouping, merging, reshaping, and
aggregating data. These operations can be performed efficiently on large datasets,
enabling users to clean and transform data easily.
 4. **Missing Data Handling**: Pandas offers robust tools for handling missing data,
allowing users to fill, drop, or interpolate missing values in datasets. This feature is
crucial for data preprocessing and analysis, ensuring data integrity and accuracy.
 5. **Time Series Functionality**: Pandas includes powerful tools for working with time
series data, such as date/time indexing, resampling, time shifting, and time zone
handling. These functionalities make pandas well-suited for analyzing time series data
and financial data.
 6. **Data Alignment**: Pandas automatically aligns data based on label indices, making
it easy to perform operations on datasets with different shapes and sizes. This feature
simplifies data manipulation and calculation tasks, improving productivity and code
readability.
 7. **Integration with NumPy**: Pandas is built on top of NumPy, providing seamless
integration with NumPy arrays and mathematical functions. This integration allows users
to leverage the speed and efficiency of NumPy while working with structured data using
pandas.
 8. **Input/Output Tools**: Pandas supports reading and writing data from various file
formats, including CSV, Excel, SQL databases, JSON, and HDF5. This makes it easy to
import external data sources into pandas for analysis and export processed data back to
different file formats.
 9. **Visualization**: Pandas integrates with popular data visualization libraries like
Matplotlib and Seaborn, allowing users to create insightful plots and charts directly from
pandas data structures. This feature enables users to visualize data patterns and
relationships easily.
 10. **Performance Optimization**: Pandas is designed for high performance, with
optimized algorithms and data structures that enable efficient data processing and
analysis. Users can leverage vectorized operations and parallel processing to speed up
computations on large datasets.

3) c) Explain the following with proper syntax and example entry.delete,


entry.insert.
 In Python dictionaries, there are no specific methods called `entry.delete` or
`entry.insert`. However, I can provide examples using the common dictionary methods
`pop()` and `update()` to simulate similar functionalities.
 1. **`pop()` method**: This method is used to remove an item from the dictionary
based on its key.
 Syntax:
 ```python
 dictionary.pop(key[, default])
 ```
 Example:
 ```python
 my_dict = {'a': 1, 'b': 2, 'c': 3}
 deleted_value = my_dict.pop('b')
 print(deleted_value) # Output: 2
 print(my_dict) # Output: {'a': 1, 'c': 3}
 ```
 2. **`update()` method**: This method is used to insert or update items in the
dictionary with key-value pairs from another dictionary or iterable object.
 Syntax:
 ```python
 dictionary.update(iterable)
 ```
 Example:
 ```python
 my_dict = {'a': 1, 'b': 2}
 new_entries = {'c': 3, 'd': 4}
 my_dict.update(new_entries)
 print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
 ```
 While these examples do not directly correspond to `entry.delete` and `entry.insert`,
they demonstrate how you can remove items from a dictionary and add new items to a
dictionary in Python using the `pop()` and `update()` methods, respectively.

4) d) Write a Python program to find factors of a given number.


 Here is a Python program that finds the factors of a given number:

 ```python
 def find_factors(number):
 factors = []
 for i in range(1, number + 1):
 if number % i == 0:
 factors.append(i)
 return factors

 # Input from the user
 num = int(input("Enter a number: "))

 # Call the function to find factors
 result = find_factors(num)

 print(f"The factors of {num} are: {result}")
 ```
 In this program:
 1. We define a function `find_factors` that takes a number as input and returns a list of
factors of that number.
 2. We iterate from 1 to the given number and check if the number is divisible by the
current iteration value. If it is divisible, we add that value to the list of factors.
 3. We take input from the user for the number.
 4. We call the `find_factors` function with the user input number and store the result.
 5. Finally, we print the factors of the given number.
 You can run this program and input any number to find its factors.

5) e) Write a Python script to generate Fibonacci terms using generator


function.
 Here is a Python script that generates Fibonacci terms using a generator function:
 ```python
 def fibonacci_generator():
 a, b = 0, 1
 while True:
 yield a
 a, b = b, a + b

 # Input from the user
 num_terms = int(input("Enter the number of Fibonacci terms to generate: "))

 # Generate Fibonacci terms using the generator function
 fibonacci_gen = fibonacci_generator()

 # Print the Fibonacci terms
 for _ in range(num_terms):
 print(next(fibonacci_gen))
 ```
 In this script:
 1;. We define a generator function `fibonacci_generator` that generates Fibonacci terms
infinitely using the `yield` keyword.
 2. Inside the generator function, we initialize two variables `a` and `b` to 0 and 1
respectively, and then enter an infinite loop where we yield the value of `a`, update `a`
and `b` to the next Fibonacci terms, and continue the loop.
 3. We take input from the user for the number of Fibonacci terms to generate.
 4. We create a generator object `fibonacci_gen` by calling the `fibonacci_generator`
function.
 5. We iterate `num_terms` times and print each Fibonacci term by calling
`next(fibonacci_gen)`.
 You can run this script and input the number of Fibonacci terms you want to generate.
The script will output the requested number of Fibonacci terms.

Q4) Attempt any four of the following.


1) a) How to define function in Python? Explain with suitable example.
 In Python, you can define a function using the `def` keyword followed by the function
name, parameters (if any), and a colon. The function body is then indented and contains
the code that the function will execute. You can optionally specify a return value using
the `return` keyword.
 Here is an example of defining a simple function in Python that calculates the square of a
number:

 ```python
 def calculate_square(number):
 square = number ** 2
 return square

 # Call the function
 result = calculate_square(5)
 print(f"The square of 5 is: {result}")
 ```
 In this example:
 - We define a function `calculate_square` that takes a parameter `number`.
 - Inside the function, we calculate the square of the input number and store it in the
`square` variable.
 - We then return the square value using the `return` keyword.
 - Outside the function, we call `calculate_square` with the argument `5` and store the
result in the `result` variable.
 - Finally, we print the result, which will output: `The square of 5 is: 25`.
 This is a simple example of defining a function in Python. Functions are reusable blocks
of code that can be called with different arguments to perform specific tasks.

2) b) Explain EXCEPT Clause with no exception.


 In Python, the `except` clause is used in a `try-except` block to handle exceptions that
may occur during the execution of the `try` block. However, it is also possible to have an
`except` clause with no specific exception specified. This is known as a generic exception
handler.
 When you use an `except` clause without specifying any exception type, it will catch all
exceptions that occur within the corresponding `try` block. This can be useful for
handling unexpected errors or for providing a general error message to the user.
 Here is an example of using an `except` clause with no specific exception:
 ```python
 try:
 result = 10 / 0
 except:
 print("An error occurred")
 ```
 In this example:
 - The `try` block attempts to perform a division by zero operation, which will raise a
`ZeroDivisionError`.
 - The `except` block does not specify any exception type, so it will catch any type of
exception that occurs.
 - If an exception occurs (in this case, a `ZeroDivisionError`), the generic `except` block will
be executed, and it will print "An error occurred".
 While using a generic `except` clause can be convenient for catching all types of
exceptions, it is generally recommended to specify the specific exceptions that you
expect and handle them accordingly. This allows for more precise error handling and
debugging.

3) c) Explain-IS-A relationship and It-as-A-relationship with example.


 In object-oriented programming, inheritance is a key concept that allows one class (the
subclass or derived class) to inherit attributes and methods from another class (the
superclass or base class). There are two main types of relationships that can be
established between classes through inheritance: the "IS-A" relationship and the "HAS-
A" relationship.
 1. IS-A Relationship:
 In the IS-A relationship, a subclass is a specialized version of a superclass. This means
that the subclass shares the same characteristics and behaviors as the superclass but
may have additional features or modifications. The IS-A relationship is typically used
when one class is a type of another class.
 Example of IS-A Relationship:
 ```python
 class Animal:
 def __init__(self, name):
 self.name = name

 def speak(self):
 pass

 class Dog(Animal):
 def speak(self):
 return "Woof!"

 class Cat(Animal):
 def speak(self):
 return "Meow!"

 # IS-A relationship
 dog = Dog("Buddy")
 cat = Cat("Whiskers")

 print(dog.speak()) # Output: Woof!
 print(cat.speak()) # Output: Meow!
 ```

 In this example, the classes `Dog` and `Cat` inherit from the `Animal` class. Both `Dog`
and `Cat` are specialized types of `Animal` and override the `speak` method to provide
their own implementation.
 2. HAS-A Relationship:
 In the HAS-A relationship, a class contains an instance of another class as a field or
attribute. This relationship signifies that a class "has" another class as a part of its
structure.
 Example of HAS-A Relationship:
 ```python
 class Engine:
 def __init__(self, horsepower):
 self.horsepower = horsepower

 class Car:
 def __init__(self, make, model, engine):
 self.make = make
 self.model = model
 self.engine = engine

 def start(self):
 return "Vroom!"

 # HAS-A relationship
 engine = Engine(200)
 car = Car("Toyota", "Camry", engine)

 print(car.start()) # Output: Vroom!
 print(car.engine.horsepower) # Output: 200
 ```
 In this example, the `Car` class has an attribute `engine` of type `Engine`, establishing a
HAS-A relationship. The `Car` class "has" an `Engine` as a part of its structure.
 Both IS-A and HAS-A relationships are fundamental concepts in object-oriented
programming and are used to model real-world relationships and hierarchies in software
systems.

4) d) Write a Python program to check if a given key already exists in a


dictionary. If Key exists replace with another key/value pair.
 You can achieve this by checking if the given key already exists in the dictionary. If the
key exists, you can replace it with another key/value pair. Here is a Python program to
demonstrate this:
 ```python
 # Function to check and replace key in a dictionary
 def check_and_replace_key(dictionary, key_to_check, new_key, new_value):
 if key_to_check in dictionary:
 dictionary[new_key] = new_value
 del dictionary[key_to_check]
 print(f"Key '{key_to_check}' replaced with '{new_key}' in the dictionary.")
 else:
 print(f"Key '{key_to_check}' does not exist in the dictionary.")

 # Sample dictionary
 my_dict = {'a': 1, 'b': 2, 'c': 3}

 # Key to check and new key/value pair
 key_to_check = 'b'
 new_key = 'd'
 new_value = 4

 # Check and replace key in the dictionary
 check_and_replace_key(my_dict, key_to_check, new_key, new_value)

 # Print the updated dictionary
 print("Updated Dictionary:", my_dict)
 ```
 In this program:
 - The `check_and_replace_key` function takes the dictionary, the key to check, the new
key, and the new value as parameters.
 - It checks if the `key_to_check` exists in the dictionary. If it does, it replaces the key with
the new key/value pair and prints a message. If the key does not exist, it prints a
message indicating that.
 - We define a sample dictionary `my_dict` with some initial key/value pairs.
 - We specify the key to check (`'b'`), the new key (`'d'`), and the new value (`4`).
 - We call the `check_and_replace_key` function with the specified parameters.
 - Finally, we print the updated dictionary to see the changes.
 You can modify the input dictionary, key to check, new key, and new value according to
your requirements.

5) e) Write a Python program to swap the value of two variables.


 You can swap the values of two variables in Python using a temporary variable or
without using a temporary variable. Here are two ways to achieve this:
 1. Using a Temporary Variable:
 ```python
 # Swap the values of two variables using a temporary variable
 def swap_with_temp(a, b):
 temp = a
 a=b
 b = temp
 return a, b
 # Initial values of the variables
 x=5
 y = 10
 print("Before swapping:")
 print("x =", x)
 print("y =", y)

 # Swap the values
 x, y = swap_with_temp(x, y)

 print("\nAfter swapping:")
 print("x =", x)
 print("y =", y)
 ```
 2. Without Using a Temporary Variable (Using Tuple Unpacking):
 ```python
 # Swap the values of two variables without using a temporary variable
 def swap_without_temp(a, b):
 return b, a

 # Initial values of the variables
 p = 15
 q = 20

 print("Before swapping:")
 print("p =", p)
 print("q =", q)

 # Swap the values
 p, q = swap_without_temp(p, q)

 print("\nAfter swapping:")
 print("p =", p)
 print("q =", q)
 ```
 Both of these programs demonstrate how to swap the values of two variables in Python.
You can choose the method that best suits your needs.

Q5) Write short notes on (any two).


1) a) Slicing Dictionaries.
 In Python, you can slice a dictionary using dictionary comprehension or by iterating over
the dictionary's items. Here are two common methods to slice dictionaries:
 1. Using Dictionary Comprehension:
 ```python
 # Original dictionary
 original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
 # Slicing the dictionary using dictionary comprehension
 sliced_dict = {key: value for key, value in original_dict.items() if key in ['a', 'b', 'c']}

 print("Sliced Dictionary:", sliced_dict)
 ```
 In this example, we have an original dictionary `original_dict`. We use a dictionary
comprehension to create a sliced dictionary `sliced_dict` that contains only the key-value
pairs where the key is `'a'`, `'b'`, or `'c'`.
 2. Using Iteration:
 ```python
 # Original dictionary
 original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

 # Slicing the dictionary by iterating over items
 keys_to_keep = ['a', 'b', 'c']
 sliced_dict = {key: original_dict[key] for key in keys_to_keep if key in original_dict}

 print("Sliced Dictionary:", sliced_dict)
 ```
 In this method, we specify the keys we want to keep in the sliced dictionary
(`keys_to_keep`). We then iterate over these keys and create a sliced dictionary
containing only the specified keys and their corresponding values from the original
dictionary.
 Both methods allow you to slice a dictionary based on specific keys. You can adjust the
keys or conditions based on your requirements for slicing the dictionary.

2) b) Data visualization.
 Data visualization is an important aspect of data analysis as it helps in understanding the
data, identifying patterns, trends, and relationships, and communicating insights
effectively. In Python, popular libraries such as Matplotlib, Seaborn, and Plotly can be
used for creating various types of plots and charts. Here is an example of creating a
simple bar chart using Matplotlib:
 ```python
 import matplotlib.pyplot as plt

 # Data for the bar chart
 languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
 popularity = [30, 25, 20, 15, 10]
 # Create a bar chart
 plt.figure(figsize=(8, 6))
 plt.bar(languages, popularity, color='skyblue')

 # Add labels and title
 plt.xlabel('Programming Languages')
 plt.ylabel('Popularity (%)')
 plt.title('Popularity of Programming Languages')
 plt.grid(axis='y', linestyle='--', alpha=0.7)

 # Display the plot
 plt.show()
 ```
 In this example, we use Matplotlib to create a simple bar chart showing the popularity of
different programming languages. We provide the data in lists (`languages` and
`popularity`) and use the `plt.bar()` function to create the bar chart. We then add labels,
a title, and gridlines to enhance the visualization. Finally, we display the plot using
`plt.show()`.
 You can explore other types of plots such as line charts, scatter plots, pie charts,
histograms, etc., by referring to the documentation of Matplotlib, Seaborn, or other data
visualization libraries. These libraries offer a wide range of customization options to
create visually appealing and informative visualizations for your data analysis tasks.

3) c) Custom Exception.
 In Python, you can create custom exceptions by defining a new class that inherits from
the built-in `Exception` class or any other existing exception class. Here is an example of
how to create a custom exception in Python:
 ```python
 # Define a custom exception class
 class CustomError(Exception):
 def __init__(self, message="A custom error occurred"):
 self.message = message
 super().__init__(self.message)

 # Raise the custom exception
 def divide_numbers(num1, num2):
 if num2 == 0:
 raise CustomError("Division by zero is not allowed")
 return num1 / num2

 # Test the custom exception
 try:
 result = divide_numbers(10, 0)
 except CustomError as e:
 print("Custom Exception:", e)
 else:
 print("Result:", result)
 ```
 In this example, we define a custom exception class `CustomError` that inherits from the
`Exception` class. We provide an optional `message` parameter that allows us to
customize the error message. Inside the `divide_numbers` function, we check if the
second number is zero, and if so, we raise our custom exception with a specific error
message.
 When we call the `divide_numbers` function with `10` and `0`, it will raise the
`CustomError` exception with the message "Division by zero is not allowed". We catch
this exception using a `try-except` block and handle it accordingly.
 By creating custom exceptions, you can make your code more robust and provide
meaningful error messages for specific scenarios in your applications.

Paper-2 [5803-505]

Que1) Attempt any Eight of the following:


1) a) What are the properties of a Dictionary?
 In Python, a dictionary is a versatile and powerful data structure that stores key-value
pairs. Here are some key properties of dictionaries:
 1. **Unordered**: Dictionaries are unordered collections of items. Unlike lists, the
elements in a dictionary are stored in any particular not order. When iterating over a
dictionary, the order of items may vary.
 2. **Mutable**: Dictionaries are mutable, meaning you can add, remove, or update key-
value pairs after the dictionary is created. This allows for dynamic changes to the
dictionary's contents.
 3. **Key-Value Pairs**: Each element in a dictionary is a key-value pair, where the key is
used to access the corresponding value. Keys are unique within a dictionary, but values
can be duplicated.
 4. **Keys**: Dictionary keys must be immutable objects, such as strings, numbers, or
tuples. This requirement ensures that keys are hashable and can be used to efficiently
retrieve values from the dictionary.
 5. **Values**: Dictionary values can be of any data type and can be mutable or
immutable. Values can be accessed and modified using their corresponding keys.
 6. **Dynamic Sizing**: Dictionaries can dynamically resize to accommodate new key-
value pairs as needed. The size of a dictionary can grow or shrink based on the number
of elements it contains.
 7. **Efficient Lookups**: Dictionaries provide fast lookups for retrieving values based on
keys. This is achieved through hash tables, which allow for constant-time access to
elements based on their keys.
 8. **Versatile Data Structure**: Dictionaries are commonly used for mapping
relationships between keys and values, storing configuration settings, representing JSON-
like data structures, and more. They offer a flexible way to organize and access data in
Python.

2) b) Write the use of an import statement with an example.


 In Python, the `import` statement is used to bring external modules or packages into
your current script or program. This allows you to access functions, classes, and other
resources defined in those modules. Here is an example demonstrating the use of the
`import` statement:
 ```python
 # Importing the math module
 import math

 # Using functions from the math module
 print(math.sqrt(16)) # Output: 4.0
 print(math.pi) # Output: 3.141592653589793

 # Importing specific functions from a module
 from random import randint
 print(randint(1, 10)) # Output: Random integer between 1 and 10

 # Importing a module with an alias
 import datetime as dt
 current_date = dt.date.today()
 print(current_date) # Output: Current date in YYYY-MM-DD format
 ```
 In this example:
 - We first import the `math` module, which provides mathematical functions and
constants.
 - We use functions like `math.sqrt()` and `math.pi` from the `math` module to calculate
the square root of a number and retrieve the value of pi.
 - Next, we import the `randint` function from the `random` module directly, allowing us
to generate random integers.
 - Finally, we import the `datetime` module with an alias `dt` for convenience and use it to
get the current date.
 By using the `import` statement, you can access the functionality provided by external
modules and leverage their capabilities in your Python code. It helps in organizing code,
reusing existing functionality, and extending the capabilities of your programs.

3) c) Differentiate between Python list and NumPy array.

4) d) What is scikit-learn?
 Scikit-learn is a popular open-source machine learning library for Python. It is built on
top of NumPy, SciPy, and Matplotlib, and provides a wide range of machine learning
algorithms and tools for tasks such as classification, regression, clustering,
dimensionality reduction, and more. Scikit-learn is designed to be user-friendly, efficient,
and accessible to both beginners and experienced machine learning practitioners.
 Key features of scikit-learn include:
 1. **Simple and Consistent API**: Scikit-learn provides a consistent and easy-to-use API
for training, testing, and deploying machine learning models. This makes it
straightforward to experiment with different algorithms and techniques.
 2. **Wide Range of Algorithms**: The library includes a variety of supervised and
unsupervised learning algorithms, including linear models, support vector machines,
decision trees, random forests, clustering algorithms, and more. This allows users to
choose the most suitable algorithm for their specific task.
 3. **Model Evaluation and Selection**: Scikit-learn provides tools for model evaluation,
hyperparameter tuning, cross-validation, and performance metrics. This helps users
assess the performance of their models and select the best configuration for their data.
 4. **Feature Extraction and Transformation**: The library offers utilities for feature
extraction, preprocessing, and transformation, including methods for handling missing
values, scaling data, encoding categorical variables, and more.
 5. **Integration with Other Libraries**: Scikit-learn integrates well with other Python
libraries such as NumPy, SciPy, Pandas, and Matplotlib, allowing for seamless data
manipulation, visualization, and analysis in machine learning workflows.
 6. **Active Development and Community Support**: Scikit-learn is actively maintained
and supported by a vibrant community of developers and machine learning enthusiasts.
Regular updates, bug fixes, and new features ensure that the library stays current with
the latest advancements in the field.
5) e) Write the definition of class method.
 A class method in Python is a method that is bound to the class rather than an instance
of the class. It can be called on the class itself or on an instance of the class. Class
methods are defined using the `@classmethod` decorator and have a special first
parameter conventionally named `cls`, which refers to the class itself.
 Here is the definition of a class method in Python:
 "A class method in Python is a method that is associated with the class itself rather than
with instances of the class. It is defined using the `@classmethod` decorator and takes
the class (conventionally named `cls`) as its first parameter. Class methods can access
and modify class-level variables and perform operations that are not specific to
individual instances of the class."
 Here is an example demonstrating the use of a class method in Python:

 ```python
 class MyClass:
 class_variable = 0

 def __init__(self, value):
 self.instance_variable = value

 @classmethod
 def increment_class_variable(cls):
 cls.class_variable += 1

 # Accessing the class method on the class itself
 MyClass.increment_class_variable()
 print(MyClass.class_variable) # Output: 1

 # Accessing the class method on an instance of the class
 obj1 = MyClass(10)
 obj1.increment_class_variable()
 print(obj1.class_variable) # Output: 2
 ```
 In this example:
 - We define a class method `increment_class_variable` using the `@classmethod`
decorator, which increments the `class_variable` belonging to the class.
 - We demonstrate calling the class method both on the class itself
(`MyClass.increment_class_variable()`) and on an instance of the class
(`obj1.increment_class_variable()`).
 - The class method can access and modify the `class_variable`, which is shared among all
instances of the class.
 Class methods are useful for defining methods that operate on the class itself or perform
tasks that are not specific to individual instances.

6) f) Write the syntax of the Raise statement & explain it.


 The `raise` statement in Python is used to raise an exception explicitly. It allows you to
create custom exceptions or handle exceptional situations in your code by interrupting
the normal flow of execution and triggering an error condition. The `raise` statement
takes an exception instance or an exception class followed by an optional error message.
 Here is the syntax of the `raise` statement in Python:
 ```python
 raise ExceptionClassName("Error message")
 ```
 - `ExceptionClassName`: This can be the name of a built-in exception class like
`ValueError`, `TypeError`, `NameError`, or a custom exception class that you have
defined.
 - `"Error message"`: This is an optional message that provides additional information
about the error that occurred. It helps in identifying the cause of the exception.
 When the `raise` statement is executed, the specified exception is raised and the
program flow is transferred to the nearest enclosing `try` block that can handle the
exception. If no suitable `except` block is found to handle the raised exception, the
program terminates and an error message is displayed.
 Here is an example demonstrating the use of the `raise` statement:
 ```python
 def divide_numbers(a, b):
 if b == 0:
 raise ZeroDivisionError("Cannot divide by zero")
 return a / b

 try:
 result = divide_numbers(10, 0)
 except ZeroDivisionError as e:
 print("Error:", e)
 ```
 In this example:
 - We define a function `divide_numbers` that takes two numbers `a` and `b` as
arguments and attempts to divide `a` by `b`.
 - If `b` is equal to zero, we raise a `ZeroDivisionError` using the `raise` statement with an
error message "Cannot divide by zero".
 - We then call the `divide_numbers` function with arguments `10` and `0` inside a `try-
except` block to handle the `ZeroDivisionError`.
 - When the division by zero occurs, the `raise` statement triggers the `ZeroDivisionError`,
and the error message "Cannot divide by zero" is printed.
 The `raise` statement is a powerful tool for handling exceptional situations in Python
code and providing meaningful error messages to aid in debugging and troubleshooting.
It allows you to control how errors are handled and provide specific information about
the cause of the exception.

7) g) List-out-Geometry methods.
8) h) What is Tkinter in Python?
 Tkinter is a standard GUI (Graphical User Interface) toolkit in Python used for creating
desktop applications with graphical interfaces. It is included with most Python
installations, making it easily accessible for developers to create interactive and visually
appealing applications.
 Tkinter is based on the Tk GUI toolkit, which is a popular cross-platform GUI library.
Tkinter provides a set of built-in widgets (buttons, labels, text boxes, etc.) that can be
used to design and build GUI applications. Developers can create windows, dialogs,
menus, and other GUI elements using Tkinter to create user-friendly applications.
 Key features of Tkinter include:
 - Simple and easy-to-use interface: Tkinter provides a simple and intuitive interface for
creating GUI applications in Python.
 - Cross-platform compatibility: Tkinter applications can run on various operating systems,
including Windows, macOS, and Linux, without requiring any modifications.
 - Customizable widgets: Tkinter offers a variety of built-in widgets that can be customized
to suit the design and functionality requirements of the application.
 - Event-driven programming: Tkinter follows an event-driven programming model, where
actions such as button clicks or key presses trigger events that can be handled by the
application.
 Here is a simple example of a Tkinter application that creates a window with a button:

 ```python
 import tkinter as tk

 def button_click():
 print("Button clicked!")

 # Create the main window
 root = tk.Tk()
 root.title("Tkinter Example")

 # Create a button widget
 button = tk.Button(root, text="Click Me", command=button_click)
 button.pack()

 # Start the main event loop
 root.mainloop()
 ```
 In this example:
 - We import the `tkinter` module and create a main window using `tk.Tk()`.
 - We define a function `button_click()` that prints a message when the button is clicked.
 - We create a button widget with the text "Click Me" and associate the `button_click()`
function with the button using the `command` parameter.
 - Finally, we start the main event loop with `root.mainloop()` to display the window and
handle user interactions.
 Tkinter is a versatile and widely-used GUI toolkit in Python that enables developers to
create interactive desktop applications with ease. It is well-documented and supported,
making it a popular choice for developing GUI applications in Python.

9) i) Break and pass statement in Python.


 In Python, the `break` and `pass` statements are used to control the flow of execution in
loops and conditional statements.
 1. `break` statement:
 The `break` statement is used to exit a loop prematurely. When the `break` statement is
encountered within a loop (such as `for` or `while`), the loop is terminated immediately,
and the program execution continues with the next statement after the loop.
 Example of using `break` in a loop:
 ```python
 for i in range(5):
 if i == 3:
 break
 print(i)
 ```
 Output:
 ```
 0
 1
 2
 ```
 In this example, the loop terminates when `i` is equal to 3 because the `break` statement
is encountered.
 2. `pass` statement:
 The `pass` statement is a null operation in Python. It is used when a statement is
required syntactically but you do not want to execute any code. It is often used as a
placeholder when defining functions, classes, or conditional blocks that will be
implemented later.
 Example of using `pass` in a conditional block:
 ```python
 x = 10
 if x < 5:
 print("x is less than 5")
 else:
 pass
 ```
 In this example, the `pass` statement is used in the `else` block as a placeholder since no
action is needed when `x` is not less than 5.
 In summary:
 - `break`: Used to exit a loop prematurely.
 - `pass`: Used as a placeholder when a statement is syntactically required but no action is
needed.
 Both `break` and `pass` statements are essential for controlling the flow of execution in
Python programs, allowing developers to handle different scenarios efficiently.

10) j) Write any two common exceptions in Python.

Que 2) Attempt any Four of the following:


1) a) What is Python? What are the benefits of using Python?
 Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python
supports multiple programming paradigms, including procedural, object-oriented, and
functional programming. It has become one of the most popular programming languages
in the world, widely used in various domains such as web development, data science,
machine learning, artificial intelligence, scientific computing, and more.
 Here are some of the key benefits of using Python:
 1. **Simplicity and Readability**: Python emphasizes simplicity and readability, making
it easy to learn and write code. Its clean and expressive syntax allows developers to write
code that is easy to understand and maintain.
 2. **Versatility**: Python is a versatile language that can be used for a wide range of
applications. It has extensive standard libraries and support for third-party packages,
making it suitable for various tasks, from web development to data analysis to machine
learning.
 3. **Large and Active Community**: Python has a large and active community of
developers, researchers, and enthusiasts who contribute to its development, share
knowledge, and provide support through forums, documentation, and online resources.
 4. **Cross-Platform Compatibility**: Python is available on multiple platforms, including
Windows, macOS, and Linux, allowing developers to write code that can run seamlessly
on different operating systems without modification.
 5. **Extensive Standard Library**: Python comes with a comprehensive standard library
that provides modules and functions for performing a wide range of tasks, from file I/O
to networking to mathematical operations, without the need for external dependencies.
 6. **Interpreted and Interactive**: Python is an interpreted language, which means that
code execution occurs line by line, making it easy to debug and test code interactively
using tools like the Python interpreter or Jupyter notebooks.
 7. **Strong Support for Integration**: Python has strong support for integrating with
other languages and platforms, allowing developers to leverage existing code and
libraries written in languages like C/C++, Java, and .NET.
 8. **Great for Prototyping and Rapid Development**: Python's simplicity and ease of
use make it ideal for prototyping and rapid development. Developers can quickly build
and test ideas without getting bogged down in low-level details.
 9. **High-Level Data Structures**: Python provides built-in high-level data structures
such as lists, dictionaries, sets, and tuples, making it easy to work with complex data and
perform various operations efficiently.
 10. **Growing Adoption in Data Science and Machine Learning**: Python has emerged
as a popular choice for data science, machine learning, and artificial intelligence due to
its rich ecosystem of libraries and frameworks such as NumPy, Pandas, TensorFlow, and
PyTorch, which provide powerful tools for data manipulation, analysis, and modeling.

2) b) Name any five built in modules in Python.


 Here are five built-in modules in Python:
 1. **math**: Provides mathematical functions and constants for performing
mathematical operations.
 2. **random**: Offers functions for generating random numbers, shuffling sequences,
and selecting random elements.
 3. **datetime**: Allows manipulation of dates, times, and time intervals, as well as
formatting and parsing of date/time strings.
 4. **os**: Provides functions for interacting with the operating system, such as file
operations, directory manipulation, and environment variables.
 5. **sys**: Offers access to system-specific parameters and functions, including
command-line arguments, standard input/output, and the Python runtime environment.
 These modules come pre-installed with Python and can be imported and used in your
Python scripts and programs without requiring additional installation.

3) c) Write in brief anonymous functions.


 Anonymous functions in Python, also known as lambda functions, are small, inline
functions that do not have a name. They are defined using the `lambda` keyword and are
often used for short, one-time operations where creating a full-fledged named function
would be unnecessary or cumbersome.
 Here's a brief overview of anonymous functions in Python:
 1. **Syntax**: Lambda functions are defined using the `lambda` keyword, followed by a
list of parameters (if any), a colon (`:`), and the expression to be evaluated. The syntax is:
`lambda parameters: expression`.
 2. **Single Expression**: Lambda functions can only contain a single expression, which
is evaluated and returned when the function is called.
 3. **No Return Statement**: Lambda functions implicitly return the value of the
expression without requiring an explicit `return` statement.
 4. **Usage**: Lambda functions are commonly used as arguments to higher-order
functions like `map()`, `filter()`, and `sorted()`, where a simple function is required as
input. They are also used in situations where a short, inline function is more appropriate
than defining a separate named function.
 5. **Scope**: Lambda functions have their own local scope, similar to regular named
functions. They can access variables from the surrounding scope (i.e., variables defined
outside the lambda function) using Python's closure mechanism.
 Example:
 ```python
 # Define a lambda function to compute the square of a number
 square = lambda x: x ** 2

 # Call the lambda function
 result = square(5)
 print(result) # Output: 25
 ```
 In this example, `lambda x: x ** 2` defines a lambda function that takes one argument `x`
and returns its square. The lambda function is assigned to the variable `square`, which
can then be called like a regular function.

4) d) What is inheritance? Write its benefits and syntax.


 Inheritance is a fundamental concept in object-oriented programming (OOP) where a
new class (called a subclass or derived class) is created based on an existing class (called
a superclass or base class). The subclass inherits the attributes and behaviors (methods)
of the superclass, allowing the subclass to reuse and extend the functionality of the
superclass.
 **Benefits of Inheritance:**
 1. **Code Reusability**: Inheritance promotes code reusability by allowing subclasses to
inherit attributes and methods from their superclass. This avoids duplication of code and
encourages a modular and DRY (Don't Repeat Yourself) coding style.
 2. **Modularity and Extensibility**: Inheritance facilitates modularity and extensibility
by organizing classes into a hierarchy of related classes. Subclasses can extend or
override the behavior of their superclass, allowing for incremental changes and
specialization without modifying the original code.
 3. **Polymorphism**: Inheritance enables polymorphic behavior, where objects of
different classes can be treated uniformly through a common interface. This promotes
flexibility and allows for more generic and flexible code.
 4. **Encapsulation**: Inheritance supports encapsulation by allowing access to the
superclass's attributes and methods through inheritance, while also providing the
flexibility to encapsulate and protect implementation details within each class.
 **Syntax of Inheritance in Python:**
 In Python, inheritance is implemented using the following syntax:

 ```python
 class BaseClass:
 # Base class attributes and methods

 class DerivedClass(BaseClass):
 # Derived class attributes and methods
 ```
 In this syntax:
 - `BaseClass` is the superclass or base class.
 - `DerivedClass` is the subclass or derived class that inherits from `BaseClass`.
 - `DerivedClass` can access the attributes and methods of `BaseClass`.
 - To indicate inheritance, the name of the superclass is specified in parentheses after the
name of the subclass during class definition (`class DerivedClass(BaseClass)`).
 Example:
 ```python
 class Animal:
 def sound(self):
 print("Animal makes a sound")

 class Dog(Animal):
 def sound(self):
 print("Dog barks")

 # Create an instance of Dog class
 dog = Dog()
 dog.sound() # Output: Dog barks
 ```
 In this example, the `Dog` class inherits from the `Animal` class. The `Dog` class overrides
the `sound()` method of the `Animal` class with its own implementation. When we call
the `sound()` method on an instance of the `Dog` class, it prints "Dog barks" instead of
the default "Animal makes a sound" from the `Animal` class.

5) e) Explain-frame widget in Tkinter with an example.


 In Tkinter, the `Frame` widget is used to organize and group other widgets together. It
acts as a container or a window within a window, allowing you to arrange and manage
the layout of widgets more effectively. You can think of a `Frame` as a rectangular region
used to group related widgets and control their arrangement and appearance.
 Here's how you can use the `Frame` widget in Tkinter with an example:

 ```python
 import tkinter as tk

 # Create the main application window
 root = tk.Tk()
 root.title("Frame Widget Example")

 # Create a frame widget
 frame = tk.Frame(root, bg="lightblue", padx=20, pady=20)
 frame.pack(padx=10, pady=10)

 # Add widgets (e.g., labels, buttons) to the frame
 label1 = tk.Label(frame, text="Hello,")
 label1.grid(row=0, column=0)

 label2 = tk.Label(frame, text="Tkinter!")
 label2.grid(row=0, column=1)

 button = tk.Button(frame, text="Click Me")
 button.grid(row=1, columnspan=2)

 # Start the Tkinter event loop
 root.mainloop()
 ```
 In this example:
 1. We create the main application window using `tk.Tk()`.
 2. We create a `Frame` widget called `frame` and specify its parent as the main window
(`root`). We also set the background color (`bg`), padding (`padx` and `pady`), and then
pack it into the main window using `frame.pack()`.
 3. We add widgets (a couple of labels and a button) to the frame using the `grid()`
method to specify their layout within the frame. The `grid()` method arranges widgets in
a grid-like pattern of rows and columns.
 4. Finally, we start the Tkinter event loop with `root.mainloop()` to display the window
and handle user events.
 In this example, the `Frame` widget (`frame`) acts as a container for the labels and the
button. It provides a visual grouping for these widgets and allows you to manage their
layout collectively. The background color and padding specified for the frame help
distinguish it from the rest of the window and provide visual separation.

Q3) Attempt any Four of the following:


1) a) What are lists and tuples? What is the key difference between the two?
 Lists and tuples are both data structures in Python used to store collections of items.
However, there are some key differences between them:
 1. **Lists**:
 - Lists are mutable, meaning their elements can be modified after the list is created.
 - Lists are defined using square brackets `[]`.
 - Lists are typically used when you have a collection of items that may need to be
modified, reordered, or appended.
 - Example: `my_list = [1, 2, 3, 'a', 'b', 'c']`
 2. **Tuples**:
 - Tuples are immutable, meaning their elements cannot be modified after the tuple is
created.
 - Tuples are defined using parentheses `()`, although they can also be defined without
any brackets.
 - Tuples are typically used when you have a collection of items that should not be
changed, such as coordinates, database records, or function arguments.
 - Example: `my_tuple = (1, 2, 3, 'a', 'b', 'c')`
 The key difference between lists and tuples is their mutability: lists can be modified after
creation, while tuples cannot. This means that once a tuple is created, you cannot
change, add, or remove its elements. Lists, on the other hand, offer more flexibility as
you can modify them freely.
 Here's a summary of the differences:

 | | Lists | Tuples |
 |------------|----------------------------------------|-----------------------------------------|
 | Mutability | Mutable (can be modified after creation) | Immutable (cannot be modified
after creation) |
 | Syntax | Defined using square brackets `[]` | Defined using parentheses `()` or
without any brackets |
 | Typical Use| When you need a mutable collection of items | When you need an
immutable collection of items |
 In summary, use lists when you need a collection of items that can be modified, and use
tuples when you need a collection of items that should remain constant.

2) b) What are the common built in data types in Python?


 Python has several built-in data types that are commonly used. Each data type has its
own set of operations and methods for manipulation and processing. Additionally,
Python also supports complex numbers (`complex`) for representing numbers with a real
and imaginary part, and bytes (`bytes`) and byte arrays (`bytearray`) for working with
binary data.
Some of the most common ones include:
 1. **Integer (`int`)**: Represents whole numbers, both positive and negative.
 2. **Float (`float`)**: Represents floating-point numbers, which include decimal points
or use scientific notation.
 3. **String (`str`)**: Represents a sequence of characters enclosed within single quotes
(''), double quotes ("") or triple quotes (''' or """).
 4. **Boolean (`bool`)**: Represents a boolean value, which can either be `True` or
`False`.
 5. **List (`list`)**: Represents an ordered collection of items, which can be of different
types. Lists are mutable.
 6. **Tuple (`tuple`)**: Represents an ordered collection of items, similar to a list, but
tuples are immutable.
 7. **Dictionary (`dict`)**: Represents a collection of key-value pairs. Keys are unique and
immutable, while values can be of any data type.
 8. **Set (`set`)**: Represents an unordered collection of unique items. Sets do not allow
duplicate elements.
 9. **NoneType (`None`)**: Represents the absence of a value or a null value.

3) c) Which are built in exceptions in Python?


 In Python, built-in exceptions are predefined error types that are raised when certain
errors occur during the execution of a program. Some of the commonly used built-in
exceptions in Python include:
 1. `SyntaxError`: Raised when there is a syntax error in the code.
 2. `IndentationError`: Raised when there is incorrect indentation in the code.
 3. `NameError`: Raised when a local or global name is not found.
 4. `TypeError`: Raised when an operation or function is applied to an object of
inappropriate type.
 5. `ValueError`: Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value.
 6. `ZeroDivisionError`: Raised when the second operand of a division or modulo
operation is zero.
 7. `IndexError`: Raised when a sequence subscript is out of range.
 8. `KeyError`: Raised when a dictionary key is not found.
 9. `FileNotFoundError`: Raised when a file or directory is requested but cannot be found.
 10. `IOError`: Raised when an I/O operation (such as opening or reading a file) fails.
 These are just a few examples; Python has many more built-in exceptions to handle
various types of errors. You can find a comprehensive list in the Python documentation.
4) d) Write the principles of keras.
 Keras is a high-level neural networks API written in Python and capable of running on top
of TensorFlow, CNTK, or Theano. It provides an easy-to-use interface for building,
training, evaluating, and deploying deep learning models. The principles of Keras can be
summarized as follows:
 1. **User Friendliness**: Keras is designed to be user-friendly, allowing developers to
quickly prototype deep learning models with minimal code. It offers a simple and
consistent API that abstracts away the complexities of building neural networks.
 2. **Modularity**: Keras encourages a modular approach to building neural networks. It
provides a wide range of pre-built layers, activation functions, optimizers, loss functions,
and utilities that can be easily combined to create custom models.
 3. **Flexibility**: Keras is highly flexible and allows for easy customization of models and
training procedures. Developers can easily experiment with different architectures, loss
functions, optimizers, and regularization techniques.
 4. **Compatibility**: Keras is compatible with multiple backends, including TensorFlow,
CNTK, and Theano. This allows developers to choose the backend that best suits their
needs without having to rewrite their code.
 5. **Scalability**: Keras supports both CPU and GPU acceleration, allowing for efficient
training of deep learning models on large datasets. It also supports distributed training
across multiple GPUs and machines.
 6. **Extensibility**: Keras is highly extensible and allows developers to create custom
layers, callbacks, metrics, and other components. This makes it easy to integrate Keras
with existing codebases and libraries.
 7. **Integration**: Keras seamlessly integrates with other popular Python libraries, such
as NumPy, Pandas, and scikit-learn. It also integrates with high-level frameworks like
TensorFlow Extended (TFX) for end-to-end machine learning pipelines.
 8. **Community Support**: Keras has a large and active community of developers and
researchers who contribute to its development and provide support through forums,
documentation, and tutorials.

5) e) Write a Python program to display current date and time.


 You can use Python's built-in `datetime` module to display the current date and time.
Here's a simple Python program to achieve that:
 ```python
 import datetime

 # Get current date and time
 current_datetime = datetime.datetime.now()

 # Print current date and time
 print("Current Date and Time:", current_datetime)
 ```
 This program imports the `datetime` module and uses the `datetime.now()` function to
obtain the current date and time. Then, it prints the obtained date and time using the
`print()` function.
 When you run this program, it will display the current date and time in the format `YYYY-
MM-DD HH:MM:SS.mmmmmm`, where:
 - `YYYY` is the year
 - `MM` is the month
 - `DD` is the day
 - `HH` is the hour in 24-hour format
 - `MM` is the minute
 - `SS` is the second
 - `mmmmmm` is the microsecond
 You can customize the output format using various methods provided by the `datetime`
module if you want a different format for displaying the date and time.

Q4) Attempt any Four of the following:


1) a) Which are the built in exceptions in Python?
 In Python, built-in exceptions are predefined error types that are raised when certain
errors occur during the execution of a program. Some of the commonly used built-in
exceptions in Python include:
 1. `SyntaxError`: Raised when there is a syntax error in the code.
 2. `IndentationError`: Raised when there is incorrect indentation in the code.
 3. `NameError`: Raised when a local or global name is not found.
 4. `TypeError`: Raised when an operation or function is applied to an object of
inappropriate type.
 5. `ValueError`: Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value.
 6. `ZeroDivisionError`: Raised when the second operand of a division or modulo
operation is zero.
 7. `IndexError`: Raised when a sequence subscript is out of range.
 8. `KeyError`: Raised when a dictionary key is not found.
 9. `FileNotFoundError`: Raised when a file or directory is requested but cannot be found.
 10. `IOError`: Raised when an I/O operation (such as opening or reading a file) fails.
 These are just a few examples; Python has many more built-in exceptions to handle
various types of errors. You can find a comprehensive list in the Python documentation.

2) b) Explain the features of pandas in Python?


 Pandas is a powerful and widely-used open-source data manipulation and analysis
library for Python. It provides easy-to-use data structures and functions designed to
make working with structured data fast, easy, and expressive. Here are some of the key
features of pandas:
 1. **DataFrame**: Pandas introduces the DataFrame data structure, which is a two-
dimensional labeled data structure with columns of potentially different types. It is
similar to a spreadsheet or SQL table, and it is the primary object for data manipulation
in pandas.
 2. **Series**: A Series is a one-dimensional labeled array capable of holding any data
type. It is similar to a one-column DataFrame but with only row labels.
 3. **Data Alignment**: Pandas automatically aligns data based on label indices, making
it easy to perform arithmetic operations and data manipulation across different datasets.
 4. **Data Input/Output**: Pandas provides functions to read data from various file
formats such as CSV, Excel, SQL databases, JSON, HTML, and more. It also supports
writing data back to these formats.
 5. **Data Cleaning and Preprocessing**: Pandas offers a wide range of functions for
cleaning and preprocessing data, including handling missing values, removing duplicates,
transforming data, and more.
 6. **Data Manipulation**: Pandas provides powerful tools for data manipulation,
including indexing, slicing, filtering, sorting, grouping, reshaping, merging, joining, and
pivoting datasets.
 7. **Data Visualization**: While pandas itself doesn't provide visualization capabilities, it
integrates seamlessly with other libraries such as Matplotlib and Seaborn, allowing users
to create various types of plots and visualizations directly from pandas data structures.
 8. **Time Series and Date Functionality**: Pandas provides robust support for working
with time series data, including date range generation, frequency conversion,
resampling, shifting, and rolling window operations.
 9. **Statistical and Mathematical Functions**: Pandas includes a wide range of statistical
and mathematical functions for analyzing data, including descriptive statistics,
correlation analysis, aggregation functions, and more.
 10. **Integration with Other Libraries**: Pandas integrates well with other libraries in
the Python ecosystem, such as NumPy, Scikit-learn, Statsmodels, and more, enabling
seamless data analysis workflows.
 Overall, pandas is a versatile and powerful library that simplifies data manipulation and
analysis tasks in Python, making it a popular choice for data scientists, analysts, and
developers working with structured data.

3) c) Define an abstract class shape and its subclass (square / circle). The
subclass has an init function which takes an argument (length/radius) Both
classes have an area & volume function which can print the area and
volume of shape where the area of shape by default 0.
 Here's how you can define an abstract class `Shape` and its subclasses `Square` and
`Circle` in Python, along with methods to calculate area and volume:

 ```python
 import abc

 class Shape(abc.ABC):
 def __init__(self):
 pass

 @abc.abstractmethod
 def area(self):
 pass

 @abc.abstractmethod
 def volume(self):
 pass

 class Square(Shape):
 def __init__(self, length):
 super().__init__()
 self.length = length

 def area(self):
 return self.length * self.length

 def volume(self):
 return 0 # Volume of 2D shape is 0

 class Circle(Shape):
 def __init__(self, radius):
 super().__init__()
 self.radius = radius

 def area(self):
 return 3.14 * self.radius * self.radius

 def volume(self):
 return 0 # Volume of 2D shape is 0

 # Example usage
 square = Square(5)
 print("Square Area:", square.area()) # Output: Square Area: 25
 print("Square Volume:", square.volume()) # Output: Square Volume: 0

 circle = Circle(3)
 print("Circle Area:", circle.area()) # Output: Circle Area: 28.26
 print("Circle Volume:", circle.volume()) # Output: Circle Volume: 0
 ```
 In this code:
 - `Shape` is defined as an abstract class using Python's `abc` module.
 - `Square` and `Circle` are subclasses of `Shape`.
 - Each subclass (`Square` and `Circle`) has its own `__init__` method that takes the
necessary parameters (`length` for `Square` and `radius` for `Circle`).
 - Both subclasses implement the abstract methods `area()` and `volume()` to calculate
the area and volume of the shape. Since a 2D shape has no volume, the `volume()`
method returns 0 by default.
 - Example usage demonstrates how to create instances of `Square` and `Circle` classes
and calculate their areas and volumes.
4) d) Write a Python program to check whether a number is in a given range.
 Here's a Python program to check whether a number is within a given range:
 ```python
 def check_range(number, start, end):
 """
 Check if the given number is within the specified range.

 Parameters:
 number (int): The number to check.
 start (int): The start of the range.
 end (int): The end of the range.
 Returns:
 bool: True if the number is within the range, False otherwise.
 """
 if start <= number <= end:
 return True
 else:
 return False
 # Example usage
 number_to_check = 7
 start_of_range = 1
 end_of_range = 10

 if check_range(number_to_check, start_of_range, end_of_range):
 print(f"{number_to_check} is within the range {start_of_range}-{end_of_range}.")
 else:
 print(f"{number_to_check} is not within the range {start_of_range}-{end_of_range}.")
 ```
 This program defines a function `check_range()` that takes three parameters: `number`
(the number to check), `start` (the start of the range), and `end` (the end of the range). It
then checks if the `number` is within the specified range by using a comparison
statement (`start <= number <= end`). If the number is within the range, the function
returns `True`; otherwise, it returns `False`.
 You can replace `number_to_check`, `start_of_range`, and `end_of_range` with the
values you want to check.

5) e) Write a Python class to find the validity of a string of parentheses, '(', ')',
'{', '}', '[', ']'. These brackets must be closed in the correct order for example
"()" and "() []{}" are valid but "[)", "({D]" and "{{{" are invalid.
 You can implement a Python class to find the validity of a string of parentheses using a
stack data structure. Here's a possible implementation:
 ```python
 class ValidParentheses:
 def __init__(self):
 self.opening_brackets = {'(', '[', '{'}
 self.closing_brackets = {')', ']', '}'}
 self.matching_brackets = {'(': ')', '[': ']', '{': '}'}

 def is_valid(self, s: str) -> bool:
 stack = []
 for char in s:
 if char in self.opening_brackets:
 stack.append(char)
 elif char in self.closing_brackets:
 if not stack:
 return False # No opening bracket to match
 last_opening_bracket = stack.pop()
 if self.matching_brackets[last_opening_bracket] != char:
 return False # Mismatched brackets
 return len(stack) == 0 # True if all brackets are matched

 # Example usage
 valid_parentheses_checker = ValidParentheses()
 print(valid_parentheses_checker.is_valid("()")) # Output: True
 print(valid_parentheses_checker.is_valid("()[]{}")) # Output: True
 print(valid_parentheses_checker.is_valid("[)")) # Output: False
 print(valid_parentheses_checker.is_valid("({D]")) # Output: False
 print(valid_parentheses_checker.is_valid("{{{")) # Output: False
 ```
 In this implementation:
 - The `ValidParentheses` class defines the necessary attributes and methods for checking
the validity of parentheses.
 - The `is_valid` method takes a string `s` containing parentheses and iterates through
each character.
 - It uses a stack to keep track of opening brackets encountered so far.
 - When encountering an opening bracket, it pushes it onto the stack.
 - When encountering a closing bracket, it pops the top element from the stack and
checks if it matches the current closing bracket. If there is no match or if the stack is
empty, it returns `False`.
 - After iterating through all characters, it returns `True` if the stack is empty (indicating all
opening brackets have been matched with closing brackets) and `False` otherwise.

Q5) Write a short note on Any Two of the following:


1) a) Package
 In Python, a package is a way to structure and organize modules (Python files) in a
hierarchical manner. A package can contain multiple modules and subpackages, allowing
developers to organize their code into logical units for better maintainability and
reusability.
 Key points about packages in Python:
 1. Package Structure: A package is a directory that contains a special file named
`__init__.py`. This file can be empty or can contain initialization code for the package.
The presence of `__init__.py` indicates to Python that the directory should be treated as
a package.
 2. Subpackages: A package can have subpackages, which are subdirectories containing
their own `__init__.py` files. This allows for a nested hierarchy of packages and modules.
 3. **Importing Modules from Packages**: Modules within a package can be imported
using dot notation. For example, if a package named `mypackage` contains a module
named `mymodule`, it can be imported as `import mypackage.mymodule`.
 4. **`__init__.py`**: The `__init__.py` file can contain initialization code that is executed
when the package is imported. It can also be used to specify which modules to import
when the package is imported using `from package import *`.
 5. **Namespace Management**: Packages help in managing namespaces by organizing
related modules and avoiding naming conflicts. Each package forms a separate
namespace.
 Example of a simple package structure:
 ```
 my_package/
 __init__.py
 module1.py
 module2.py
 subpackage/
 __init__.py
 submodule1.py
 ```
 To import modules from this package:
 ```python
 import my_package.module1
 from my_package.subpackage import submodule1
 ```
 Packages are a fundamental concept in Python for organizing and structuring code in a
modular and scalable way. They help in creating well-organized projects, promoting code
reuse, and simplifying maintenance.

2) b) Assertion
 In Python, the `assert` statement is used as a debugging aid to test assumptions in code.
It allows you to test conditions that should always be true during the execution of the
program. If the condition is not met, an `AssertionError` exception is raised, indicating a
bug in the program.
 The syntax of the `assert` statement is:
 ```python
 assert condition, message
 ```
 - `condition`: The expression that should evaluate to `True`. If it evaluates to `False`, an
`AssertionError` is raised.
 - `message` (optional): An optional message that can provide more information about
the assertion failure. This message is displayed when the assertion fails.
 Example of using `assert`:
 ```python
 x = 10
 assert x > 0, "x should be greater than 0"
 print("x is positive")
 ```
 In this example:
 - The `assert x > 0, "x should be greater than 0"` statement checks if the value of `x` is
greater than 0. If the condition is `False`, an `AssertionError` with the message "x should
be greater than 0" is raised.
 - If the condition is `True`, the program continues to execute the next statement.
 It's important to note that assertions are typically used during development and testing
to catch logical errors or assumptions that should hold true. They can be disabled in
production code by running the Python interpreter with the `-O` (optimize) flag or by
setting the `PYTHONOPTIMIZE` environment variable to a non-zero value.
 While assertions can help in debugging and testing code, they should not be used for
error handling or input validation in production code. Instead, exceptions should be used
for handling expected errors and validating user input.

3) c) Tuple
 In Python, a tuple is an ordered collection of elements, similar to a list. However, tuples
are immutable, meaning that once created, their elements cannot be changed. Tuples
are defined using parentheses `()` and can contain elements of different data types.
 Key points about tuples in Python:
 1. Creating a Tuple: Tuples are created by enclosing elements in parentheses `()`.
Elements are separated by commas.
 ```python
 my_tuple = (1, 2, 'hello', 3.14)
 ```
 2.Accessing Elements: Elements in a tuple can be accessed using indexing. Indexing
starts at 0.
 ```python
 print(my_tuple[0]) # Output: 1
 ```
 3.Immutable: Tuples are immutable, so you cannot change the elements once a tuple is
created. However, you can create a new tuple based on an existing tuple.
 ```python
 my_tuple = (1, 2, 3)
 # This will raise an error
 my_tuple[0] = 10
 ```
 4.Tuple Packing and Unpacking: Tuples can be packed (combining values into a tuple) and
unpacked (assigning values of a tuple to variables) easily.
 ```python
 # Packing
 my_tuple = 1, 2, 3
 # Unpacking
 a, b, c = my_tuple
 ```
 5. Tuple Methods: Tuples have limited methods because of their immutability. Some
common methods include `count()` and `index()`.
 ```python
 my_tuple = (1, 2, 2, 3, 3, 3)
 print(my_tuple.count(2)) # Output: 2
 print(my_tuple.index(3)) # Output: 3
 ```
 6.Use Cases: Tuples are often used when you want to store a fixed collection of items
that should not be changed. They are also used for returning multiple values from a
function.
 Tuples are commonly used in Python for various purposes, such as representing fixed
collections of data, passing multiple values to functions, and as keys in dictionaries. Their
immutability makes them suitable for scenarios where you want to ensure that the data
remains constant throughout the program.

You might also like