0% found this document useful (0 votes)
47 views

Python Question Bank - Class Test 2

The document is a question bank covering various topics in Python programming, including variables, file handling, classes, inheritance, and exception handling. It provides explanations, code examples, and questions for practice, focusing on concepts like local and global variables, the use of libraries like Matplotlib and NumPy, and methods of exception handling. Additionally, it discusses data hiding and user-defined exceptions, along with practical programming tasks.

Uploaded by

idontknow23787
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Python Question Bank - Class Test 2

The document is a question bank covering various topics in Python programming, including variables, file handling, classes, inheritance, and exception handling. It provides explanations, code examples, and questions for practice, focusing on concepts like local and global variables, the use of libraries like Matplotlib and NumPy, and methods of exception handling. Additionally, it discusses data hiding and user-defined exceptions, along with practical programming tasks.

Uploaded by

idontknow23787
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

PWP Question Bank

2 Marks Questions

Q.1. Explain Local and Global variable. - 2 mks

Local Scope: A variable defined inside a function is local to that function and cannot be accessed
outside.

def f():

x = 10 # Local variable

print(x)

f()

# print(x) # Error, x is not accessible outside f()

Global Scope: A variable defined outside any function is global and can be accessed inside
functions, but to modify it inside a function, you need to use the global keyword.

x = 10 # Global variable

def f():

global x

x = 20 # Modify global variable

f()

print(x) # Output: 20

Q.2.Write the output for the following if the variable course =


“Python”
>>> course [ : 3 ]
>>> course [ 3 : ]
>>> course [ 2 : 2 ]
>>> course [ : ]
>>> course [ -1 ]
>>> course [ 1 ]
Answer -

Q.3.Write use of matplotlib package in python and give its type - 2 mks
Matplotlib is a powerful library in Python used for creating various types of plots and charts. It's
widely used for data visualization.

Common Plot Types:


Q.4.Define class and object in python with example. - 2 MKS
Class: A class is a blueprint or template for creating objects. It defines attributes (variables) and
methods (functions) that describe the behavior of the object.
Object: An object is an instance of a class. It contains real data and can use the methods defined
in the class.

Q.5.Write a Python program to demonstrate single inheritance with


diagram.
class A:
num1=int(input("Enter First Number: "))
num2=int(input("Enter Second Number: "))

def Add(self):
print("Addition: ", self.num1+self.num2)
def Sub(self):
print("Subtraction: ", self.num1-self.num2)

class B(A):
def Multi(self):
print("Multiplication: ", self.num1*self.num2)

obj=B()
obj.Add()
obj.Sub()
obj.Multi()
Q.6. Differenciate between method overloading and method overriding in
Python
Q.7. WAP to read contents of first.txt file and write same content
in the second.txt file. - 2 mks

# Open the first file in read mode and read its content
with open('first.txt', 'r') as first_file:
content = first_file.read()

# Open the second file in write mode and write the content to it
with open('second.txt', 'w') as second_file:
second_file.write(content)

print("Content has been copied from first.txt to second.txt.")

Q.8.Differentiate between readline( ) and readlines( ) functions in file-handling. - 2


mks
Q9. List 6 different modes of opening a file in Python.​
In Python, the open() function is used to open files in various modes:

●​ 'r': Read Mode → Opens the file for reading (default mode).
●​ 'w': Write Mode → Opens the file for writing. Creates a new file or overwrites an
existing file.
●​ 'a': Append Mode → Opens the file to append content. Creates a file if it doesn’t exist.
●​ 'r+': Read and Write Mode → Opens the file for both reading and writing.
●​ 'x': Exclusive Creation → Creates a file but raises an error if the file already exists.
●​ 'b': Binary Mode → Opens the file in binary mode (used with other modes).
●​ 't': Text Mode → Opens the file in text mode (default, used with other modes).

4 Marks Questions
Q.1.Explain three built-in list functions. - 4 mks

Python provides a wide range of built-in functions that simplify programming tasks. These
functions can be categorized based on their purposes, such as type conversion, mathematical
operations, etc.

1. Type Conversion Functions

These functions allow conversion between data types.

int(x)
c): Converts x to an integer.​
int("42") # Output: 42

float(x): Converts x to a float.​


float("3.14") # Output: 3.14

str(x): Converts x to a string.​


str(123) # Output: '123'

bool(x): Converts x to a boolean.​


bool(0) # Output: False
bool(1) # Output: True
2. Math Functions

Python provides basic mathematical functions in the standard library.

abs(x): Returns the absolute value of x.​


abs(-5) # Output: 5

round(x[, n]): Rounds x to n decimal places.​


round(3.14159, 2) # Output: 3.14

sum(iterable, start=0): Returns the sum of items in an iterable.​


sum([1, 2, 3]) # Output: 6

3. Utility Functions

These functions provide utility operations.

type(obj): Returns the type of an object.​


type(42) # Output: <class 'int'>

len(s): Returns the length of an object.​


len("hello") # Output: 5

range(start, stop): Returns a sequence of numbers.​


list(range(1, 5)) # Output: [1, 2, 3, 4]
id(obj): Returns the memory address of an object.​
id(42) # Output: e.g., 140377950710080
input(prompt): Accepts user input.​
name = input("Enter your name: ")

Q.2. Explain following functions with example: - 4 mks


i) The open( ) function
ii) The write( ) function

i) The open() Function

The open() function in Python is used to open a file and return a file object, which allows you to
interact with the file (reading, writing, etc.). It takes at least one argument, the file path, and
optionally a mode (to specify how the file should be opened).
ii) The write() Function

The write() function is used to write data to a file. It is available after opening a file in a write or
append mode ('w', 'a')
Q.3. Explain Numpy package in detail. 4 mks

NumPy is a key package in Python. It helps you work with arrays and matrices, which are
collections of numbers, and provides many tools to perform mathematical operations on
them efficiently.

1. NumPy Arrays

●​ Arrays: Think of arrays as grids of numbers. You can create a one-dimensional


array (like a list of numbers) or a multi-dimensional array (like a table of
numbers).

import numpy as np

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


print(arr) # Output: [1 2 3 4 5]

2. Doing Math with Arrays

●​ You can perform mathematical operations on entire arrays at once, which makes
your code shorter and faster.
arr = np.array([1, 2, 3, 4])
print(arr * 2) # Output: [2 4 6 8]

3. Accessing Parts of Arrays

●​ You can easily get parts of an array, like selecting a row from a table or a slice of a
list.

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


print(arr[1:4]) # Output: [2 3 4]

Q.4.Explainmultilevel inheritance with a diagram and write a Python


program to demonstrate the concept.

Multi Level Inheritance


Definition: Multilevel inheritance involves a chain of classes where a class derives from another
derived class. This creates a hierarchy of inheritance.

class A:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))

def Add(self):
print("Addition: ", self.num1 + self.num2)
def Sub(self):
print("Subtraction: ", self.num1 - self.num2)
class B(A):
def Multi(self):
print("Multiplication: ", self.num1 * self.num2)
def Div(self):
print("Division: ", self.num1 / self.num2)

class C(B): # Multilevel inheritance (class C inherits from class B)


def Rem(self):
print("Remainder: ", self.num1 % self.num2)

# Creating object of class C


obj = C()
obj.Add() # Inherited from class A
obj.Sub() # Inherited from class A
obj.Multi() # Inherited from class B
obj.Div() # Inherited from class B
obj.Rem() # Defined in class C

Q.5. Explain method overloading in python with example. - 4 MKS

Method Overloading (Same method name, different parameters):

Method overloading allows a class to have multiple methods with the same name but
different parameters. However, Python does not support traditional method overloading
as seen in languages like Java. Instead, Python handles similar functionality using default
arguments or by checking arguments within a single method.
Method Overriding in Python

Definition: Method overriding happens when a subclass provides its own version of a method
that is already defined in its superclass. The method in the subclass has the same name and
parameters (signature) as the method in the superclass, but it gives a new implementation.

Q.6.Define Data Hiding concept ? Write four advantages ofData Hiding.


Answer-Data hiding is an essential concept of object-oriented programming (OOP) that helps in
restricting access to certain details of an object. It is used to prevent direct modification of an
object's internal data from outside the class, ensuring that sensitive information is well-protected
and only accessible through controlled mechanisms.

By restricting direct access to data, data hiding promotes encapsulation, which enhances code
security, prevents unintended modifications, and ensures that object properties remain in a
consistent and valid state.

Advantages of Data Hiding

✅ Encapsulation: Protects data from unintended modifications.​


✅ Security: Prevents unauthorized access to sensitive information.​
✅ Data Integrity: Ensures that data remains valid and consistent.​
✅ Code Maintainability: Changes in internal implementation do not affect external code.​
✅ Better Control: Allows data access through getter and setter methods.
Q.7. Explain user defined exception and write a Python program to create user
defined exception that will check whether the password is correct or not.
User-defined exceptions are created by defining a new class that inherits from
Python’s built-in Exception class or one of its subclasses. By doing this, we can create
custom error messages and handle specific errors in a way that makes sense for our
application.

Q.8. Describe the method of handling exceptions in Python using try and
except blocks. Include an example and its syntax.
Exception Handling

Exception handling is a mechanism that prevents programs from crashing when errors
occur. An exception is an error that happens during program execution, like dividing by
zero or trying to open a missing file.

try-except Block

The try block contains the code that may cause an error, while the except block
catches and handles the exception.
Q.9.Write a Python program to open a file, write data to it, and then read the
content also mention the steps in file handling.

Steps in File Handling:

1.​ Open a file in write mode ('w').


2.​ Write data to the file.
3.​ Close the file.
4.​ Open the same file in read mode ('r').
5.​ Read and display its content.

You might also like