You are on page 1of 11

Python QB CT-2

2 Marks Questions:

1) List and explain any two standard packages of python.


Ans:- A) Numpy Package : NumPy is a fundamental package for scientific
computing with Python. It provides support for multi-dimensional arrays and
matrices, along with a collection of mathematical functions to operate on these
arrays efficiently.
B) Pandas Package : This package provides high-performance, easy-to-use data
structures and data analysis tools for the Python programming language. It's
particularly well-suited for working with structured, tabular data, such as CSV
files or SQL tables.
------------------------------------------------------------------------------------------------
2) State the Use of any four methods in math module.
Ans:- The math module in Python is a built-in module that provides a collection
of mathematical functions and constants. Various Functions of math module are:
A) math.sqrt(x): Returns the square root of a number x.
example : import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
B) math.pow(x, y): Returns the value of x raised to the power of y.
example : import math
result = math.pow(2, 3)
print("2 raised to the power of 3:", result) # Output: 8.0
C) math.ceil(x) : Returns the smallest integer greater than or equal to x
example : import math
result = math.ceil(3.2)
print("Ceiling of 3.2 is:", result) # Output: 4
D) math.floor(x): Returns the largest integer less than or equal to x.
example : import math
result = math.floor(3.7)
print("Floor of 3.7 is:", result) # Output: Floor of 3.7 is: 3

------------------------------------------------------------------------------------------------
3) Explain local and global variable.
Ans:- a) Local Variables :-
• Local variables are declared inside a function or block of code and are
accessible only within that specific function or block.
• Once the function or block execution completes, the local variable is
destroyed, and its value cannot be accessed from outside that scope.
• Example :
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
b) Global Variables :-

• Global variables are declared outside of any function or block of code and can
be accessed from any part of the program, including inside functions.
• They can be modified and assigned new values from any part of the program.
• If a variable is modified inside a function without being declared as global,
Python treats it as a new local variable within that function's scope.
• Example :
y = 20 # global variable
def my_function():
print("Inside function:", y)
my_function()
print("Outside function:", y)
------------------------------------------------------------------------------------------------
4) State the use of parameter “ self ” in python class.
Ans:-
• In python programming self is a default variable that contains the memory
address of the instance of the current class.
• The self parameter is a reference to the class itself so we can use self to refer
to all the instance variable and instance methods.
• In a class we can define variables, functions etc. While writing function in
class we have to pass atleast one argument that is called self parameter.

• class MyClass:
def init(self, value):
self.value = value
def display_value(self):
print("Value:", self.value)

def update_value(self, new_value):


self.value = new_value
print("Value updated to:", self.value)
# Create an object of the class
obj = MyClass(10)
# Call methods on the object
obj.display_value() # Output: Value: 10
# Update the value attribute
obj.update_value(20) # Output: Value updated to: 20
# Call the method again to see the updated value
obj.display_value() # Output: Value: 20
------------------------------------------------------------------------------------------------
5) Define class? How to create an class and its object in python.
Ans:-
• A class is a block of statement that combine data and operations, which are
performed on the data, into a group as a single unit and acts as a blueprint for
the creation of objects.
• Syntax to create Class and objects in Python:
class ClassName:
‘ Optional class documentation string
#list of python class variables
# Python class constructor
#Python class method definitions
# Create an object of the class
object_name = ClassName(argument1, argument2, ...)

• Example:
class student:
def display(self): # defining method in class
print("Hello Python")
s1=student() #creating object of class
s1.display() #calling method of class using object
• Output: Hello Python.
------------------------------------------------------------------------------------------------
6) Write use of try:finally block with Syntax
Ans:-
• The finally block will be executed no matter if the try block raises an error or
not.
• This can be useful to close objects and clean up resources.
• The try:finally block in Python is used to ensure that certain actions are
always performed, regardless of whether an exception occurs or not.
• Syntax:-
try:
# Code that may raise an exception
finally:
# Code that will always execute, regardless of whether an exception
occurred.
------------------------------------------------------------------------------------------------
7) List four file modes in python.
Ans:-In Python, when working with files, you typically use file modes to
specify the intention of how you want to interact with the file. Here are four
common file modes:
• Read mode: Opens a file for reading. If the file does not exist, it raises an
error.
• Write mode: Opens a file for writing. If the file exists, it truncates the file to
zero length; otherwise, it creates a new file.
• Append mode: Opens a file for appending. It creates the file if it does not
exist. The data is written at the end of the file without truncating the existing
contents.
• Binary mode: This mode is used when dealing with binary files like images,
executables, etc. It should be used in conjunction with other modes (e.g., 'rb'
for reading a binary file, 'wb' for writing a binary file).

------------------------------------------------------------------------------------------------

8) With neat example explain default constructor concept in python.


Ans:- Default constructor- The default constructor is simple constructor which
does not accept any arguments. Its definition has only one argument which is a
reference to the instance being constructed.
class MyClass:
def __init__(self):
print("Default constructor called.")
# Creating an instance of MyClass
obj = MyClass()
Output: Default constructor called.
In this example, the default constructor __init__ is called automatically when an
instance of the MyClass class is created. The output confirms that the default
constructor is indeed invoked

------------------------------------------------------------------------------------------------
4 Marks Questions:
1. Explain any four Python’s Built in Function with example.
Ans:- Python’s Built in Functions are :
• len() : This function returns the length of an object such as a string, list,
tuple, dictionary, etc.
example :
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
• type(): This function returns the type of an object.
Example :
my_integer = 10
print(type(my_integer)) # Output: <class ‘int’>
• max(): This function returns the maximum value among the arguments
provided or the maximum value in an iterable.
Example :
print(max(10, 20, 30)) # Output: 30
• min(): This function returns the minimum value among the arguments
provided or the minimum value in an iterable.
Example :
print(min(10, 20, 30)) # Output: 10
------------------------------------------------------------------------------------------------
2. Write a python program to find reverse of a given number using user
defined function.
Ans:-
def reverse_number(num):
reverse = 0
while num > 0:
digit = num % 10
reverse = (reverse * 10) + digit
num = num // 10
return reverse
number = int(input("Enter a number:
reverse = reverse_number(number)
print("Reverse of the number:", reverse)

• Output :
Enter a number: 1234
Reverse of the number: 4321
------------------------------------------------------------------------------------------------
3. Explain Module and its use in python.
Ans:-
A) A module in Python is simply a file containing Python statements and
definitions. It typically consists of functions, classes, and variables that
perform specific tasks or define reusable components.
B) Modules can be imported into other Python scripts or programs to access
their functionality.
C) Uses of Module in python :
• Organizing Code: Modules help in organizing code by grouping related
functionality together. For example, you might have a module for
handling file operations, another for mathematical computations, and so
on.
• Code Reusability: Once you've written code in a module, you can reuse
it in different parts of your program or in other programs altogether. This
promotes code reuse and helps in avoiding redundancy.
• Namespacing: Modules provide a way to create separate namespaces for
different parts of your program. This helps in avoiding naming conflicts
between different variables, functions, or classes.
• Importing: To use code from a module, you need to import it into your
program using the import statement. Once imported, you can access the
functions, classes, and variables defined in the module using dot notation
(module_name.item_name).
D) Example : Calculating the square root of a number using math module.
import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0

------------------------------------------------------------------------------------------------
4. Create a class employee with data members: name, department and
salary. Create suitable methods for reading and printing employee
information.
Ans:-
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def read_employee_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter employee department: ")
self.salary = float(input("Enter employee salary: "))
def print_employee_info(self):
print("Employee Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)

# Example usage:
if __name__ == "__main__":
emp = Employee("", "", 0.0)
emp.read_employee_info()
print("\nEmployee Information:")
emp.print_employee_info()
• output:
Enter employee name: John Doe
Enter employee department: Sales
Enter employee salary: 50000
• Employee Information:
Employee Name: John Doe
Department: Sales
Salary: 50000.0

------------------------------------------------------------------------------------------------
5. Illustrate the use of method overriding? Explain with example.
Ans ⇨ Method overriding is an ability of a class to change the
implementation of a method provided by one of its base class.
If a class inherits a method from its superclass, then there is a chance to
override the method provided.
You can always override your parent class methods.
class Parent:
def echo(self):
print('I am from Parent class')
class Child (Parent):
def echo(self):
print('I am from Child class')
p = Parent()
c = Child()
p.echo()
c.echo()
• Output:
I am from Parent class
I am from Child class

------------------------------------------------------------------------------------------------
6. Write a Python program to implement multilevel inheritance.
Ans ⇨
class Family:
def show_family(self):
print("This is our family:")
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername
class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son() # Object of Son class
s1.fathername = "Ashish"
s1.mothername = "Sonia"
s1.show_family()
s1.show_parent()

-----------------------------------------THE END--------------------------------------

You might also like