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

python qb

Uploaded by

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

python qb

Uploaded by

Nilkant Gorle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER 4:

Q1. Write a program to create a bar chart using matplotlib.

Ans:-
import matplotlib.pyplot as plt

# Data for the bar chart


fruits = ['Apple', 'Banana', 'Cherry', 'Mango']
quantities = [40, 30, 20, 50]

# Creating the bar chart


plt.bar(fruits, quantities, color=['red', 'yellow', 'pink', 'orange'])

# Adding labels and title


plt.xlabel('Fruit Names')
plt.ylabel('Quantity in Kg')
plt.title('Fruit Quantity Chart')

# Display the bar chart


plt.show()

Q2. Define and Explain Local and Global Variables with an Example.

Ans:-
local variable :-
A local variable is a variable that is declared within a specific function or block of code and
can only be used inside that function or block. It is not accessible from outside that function
or block. The main idea of a local variable is that it is meant to temporarily hold data that is
only relevant within the context of the function being executed.

Example: -

def greet():
name = "Alice" # Local variable
print("Hello,", name)

greet()
print(name) # This will cause an error!

Global Variable :-
A global variable, on the other hand, is a variable that is declared outside of any function
or block and is accessible throughout the entire program, in any function or class.
Because global variables exist in the program’s global scope, any function can access and
read the value of a global variable.
Example:-
x = 10 # Global variable

def display():
print("Inside function, x =", x)

display()
print("Outside function, x =", x)

Output: - Inside function, x = 10


Outside function, x = 10

Q3. Write a Short Note on Functions with Default Arguments.

Ans :- Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.
Python allows function arguments to have default values. If the function is called without the
argument, the argument gets its default value.
Default Arguments:
Python has a different way of representing syntax and default values for function arguments.
Default values indicate that the function argument will take that value if no argument value is
passed during the function call. The default value is assigned by using the assignment(=)
operator of the form keywordname=value.
Syntax:
def function_name(param1, param2=default_value2, param3=default_value3)

Example:-
def greet(name="User"):
print("Hello,", name)
greet("Alice") # Output: Hello, Alice
greet() # Output: Hello, User (default value used)

Q4. What is kwargs in Python? Explain with an Example.

Ans:-
The special syntax **kwargs in function definitions is used to pass a variable length
argument list. We use the name kwargs with the double star **.
• A keyword argument is where you provide a name to the variable as you pass it into
the function.
• It collects all the additional keyword arguments passed to the function and stores them
in a dictionary.

Example:-
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_details(Name="Alice", Age=25, City="New York")


Output:-
Name: Alice
Age: 25
City: New York

Q5. How to Create a Module in Python? Explain with an Example.


Ans:- A module is simply a Python file (.py) that contains functions, variables, classes, or
executable code. Instead of writing all your code in one file, you can create modules to
divide your program logically.
Python provides many built-in modules (like math, os, random), but you can also create your
own custom modules.
How to Create a Module in Python?
✅ Steps:
1. Create a Python file (e.g., my_module.py).
2. Define functions inside it.
3. Import the module in another Python file.

Example:-
Example:
Step 1: Create my_module.py

def greet(name):
return f"Hello, {name}!"

Step 2: Import and Use the Module

import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!

Q6. Explain Python’s Built-in Module: random.


Ans:-
The random module is part of Python’s standard library, which means it's available by
default — no need to install anything.
It is used to perform operations that involve randomness such as:
• Generating random numbers (integers or floats)
• Selecting random elements from a list or other collections
• Shuffling data
• Creating random samples
Function Purpose
random() Float between 0.0 and 1.0
randint(a, b) Random integer from a to b (inclusive)
uniform(a, b) Random float between a and b
choice(seq) Random element from a sequence
sample(pop, k) k unique elements from a population
shuffle(list) Shuffle elements in a list
seed(n) Reproduce the same sequence of randoms

Q7. Explain Recursive Functions in Python with an Example.

Ans:- A recursive function is a function that calls itself in order to solve a larger problem by
breaking it down into smaller, simpler sub-problems of the same type.

It’s a powerful tool in programming, especially useful for tasks that can be naturally divided
into similar subtasks, like mathematical problems, tree traversal, and more.

Key Components of a Recursive Function:


1. Base Case:
o This is the condition under which the function stops calling itself.
o Without it, recursion will go on forever and cause a stack overflow error.
2. Recursive Case:
o The part of the function where it calls itself to solve a smaller part of the
problem.
Example:-
def factorial(n):
if n == 0:
return 1 # base case
else:
return n * factorial(n - 1) # recursive case
Chapter 5:

1. State the Use of the Parameter self in a Python Class.


Ans:-
In Python, self is a special parameter used inside class methods to refer to the instance
(object) of the class itself. It acts as a reference to the current object through which we can
access the instance variables and methods.

v Purpose of self:
• It allows each object to maintain its own state (i.e., store unique values in instance
variables).
• It helps distinguish instance variables from local variables.
• It allows access to other methods and properties inside the class.

Example:-
class Student:
def __init__(self, name, age):
self.name = name # Assigning instance variable
self.age = age

def display(self):
print("Name:", self.name)
print("Age:", self.age)

s1 = Student("Alice", 20)
s1.display()

2. What is a class and object? How to create a class and its object? Explain with an
example.
Ans:-
Class:-
A class is a blueprint or template for creating objects. It defines the attributes (variables) and
methods (functions) that its objects will have.
Think of a class as a design or prototype. For example, a class Car can define properties like
color, brand, and speed, and methods like start() or stop().
✅ Key Points:
• It is created using the class keyword.
• It does not occupy memory until an object is created.
• It supports object-oriented programming concepts like inheritance, encapsulation, and
polymorphism.
Syntax:-
class ClassName:
def __init__(self, parameters):
self.attribute1 = value1
self.attribute2 = value2
# More attributes as needed
def method_name(self):
# Method body
Pass

Object:-
An object is an instance of a class.
It is a real-world entity created from the class blueprint. Each object has its own copy of
variables and can use the methods defined in the class.
✅ Key Points:
• An object is created using the class name followed by parentheses.
• Each object occupies its own memory.
• Multiple objects can be created from a single class.

Syntax:-
object_name = ClassName(arguments) # Creating an object
object_name.method_name() # Calling a method

Example:-

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("Name:", self.name)
print("Age:", self.age)

s1 = Student("Alice", 20)
s1.display()

3. Write a program to demonstrate Constructor with default arguments.


Ans:-
class Student: #class classname
def __init__(self, name="Unknown", age=18):
self.name = name
self.age = age

def display(self):
print("Name:", self.name)
print("Age:", self.age)

s1 = Student("Alice", 20) # Arguments provided


s2 = Student("Bob") # Only name provided, age will be default (18)
s3 = Student() # No arguments provided, both will be default

print("Student 1:")
s1.display()
print("\nStudent 2:")
s2.display()

print("\nStudent 3:")
s3.display()

Output:-

Student 1:
Name: Alice
Age: 20

Student 2:
Name: Bob
Age: 18

Student 3:
Name: Unknown
Age: 18

4. Write a program to demonstrate parameterized constructor in base class and derived


class.
Ans:-

# Base class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("Name:", self.name)
print("Age:", self.age)

# Derived class
class Student(Person):
def __init__(self, name, age, student_id):
# Calling base class constructor
super().__init__(name, age)
self.student_id = student_id

def display(self):
# Displaying base class attributes
super().display()
print("Student ID:", self.student_id)

# Creating an object of the derived class


s1 = Student("Alice", 20, "S12345")
# Displaying the details
s1.display()

Output:-
Name: Alice
Age: 20
Student ID: S12345

5.Write a short note on method overriding in Python.


Ans:-
1. Method Overriding happens when a child class defines a method that already exists
in its parent class.
2. The method in the child class has the same name, same parameters, and usually the
same return type as the method in the parent class.
3. When the method is called, Python decides which version to run based on the
object, not the reference.
4.
o If you use a parent class object, it runs the parent’s method.
o If you use a child class object, it runs the child’s (overridden) method.
5. This allows the child class to provide its own specific behavior for the method.
6. You can use super() inside the child class to call the parent’s version of the method,
if needed.
7. Method overriding supports runtime polymorphism, meaning the correct method is
chosen while the program is running.
8. It helps achieve code flexibility and reusability, as the same method name can
behave differently based on the class.

Example:-

class Animal:
def sound(self):
print("Animal makes a sound")

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

a = Animal()
a.sound() # Output: Animal makes a sound

d = Dog()
d.sound() # Output: Dog barks

Output:-
Animal makes a sound
Dog barks
6. Python does not allow method overloading, explain alternate ways of achieving
similar effects of method overloading.
Ans:-
Method overloading means defining multiple methods with the same name but different
parameters (number or type).
Many programming languages like Java or C++ support it directly.

Python does not support method overloading.


If you define the same method name multiple times in a class, the last one overrides the
previous ones.

Alternate Ways to Achieve Method Overloading in Python


Python allows similar behavior using default arguments, variable-length arguments, and type
checking.

7. Write a general syntax to inherit one class into another class. Explain Multiple
Inheritance with example.
Ans:-
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
class (called a child or derived class) to inherit attributes and methods from another class
(called a parent or base class). This promotes code reuse, modularity, and a hierarchical class
structure. In this article, we’ll explore inheritance in Python.

v General Syntax to Inherit One Class into Another:

class Parent:
# code

class Child(Parent):
# inherits the code from Parent

Multiple Inheritance:-

Python provides us the flexibility to inherit multiple base classes in the child class.

Multiple Inheritance means that we are inheriting the property of multiple classes into one. In
case we have two classes, say A and B, and we want to create a new class which inherits the
properties of both A and B.

So it just like a child inherits characteristics from both mother and father, in python, we can
inherit multiple classes in a single child class.
Example:-

class Father:
def father_traits(self):
print("Father: Hardworking")

class Mother:
def mother_traits(self):
print("Mother: Caring")

class Child(Father, Mother): # Multiple Inheritance


def child_traits(self):
print("Child: Inherits both traits")

c = Child()
c.father_traits()
c.mother_traits()
c.child_traits()

output:-

Father: Hardworking
Mother: Caring
Child: Inherits both traits
Chapter 6 :

1. Explain seek() and tell() functions for File pointer manipulation.


Ans:-
tell() Function – Key Points
1. The tell() function returns the current position of the file pointer.
2. The position is counted in bytes from the beginning of the file.
3. It helps track how much of the file has been read or written.
4. Useful in monitoring or storing the current location for later use.
5. Commonly used to debug file read/write operations.

Syntax of tell():-

file_object.tell()

seek() Function – Key Points


1. The seek() function is used to move (reposition) the file pointer to a specific location in
the file.
2. It allows random access to file data (i.e., non-sequential reading/writing).
3. Takes two parameters: offset (number of bytes to move) and whence (reference point).
4. The whence parameter can be:
o 0 → start of file (default),
o 1 → current position,
o 2 → end of file.
5. Essential in large files, binary files, and partial reads/writes.
6. Allows jumping forward or backward within a file (as permitted).
7. Can be used in both text and binary modes, but works more accurately in binary mode.
Syntax:-

file_object.seek(offset, whence)

2. Explain the following Python functions w.r.t Directories


a. getcwd() b. mkdir() c. chdir() d. listdir() e. exists()
Ans:-
getcwd()
FullForm:os.getcwd()
Meaning: Get Current Working Directory
• This function returns the absolute path of the current working directory, i.e., the
folder where your Python script is currently running.
• It’s useful to check where your program is working from, especially when working
with relative paths.

mkdir()
FullForm:os.mkdir(path)
Meaning: Make Directory
• This function is used to create a new single directory at the specified path.
• If the directory already exists or the parent folder doesn’t exist, it raises an error.
chdir()
FullForm:os.chdir(path)
Meaning: Change Directory
• This function is used to change the current working directory to a different path.
• After changing the directory, all relative file paths will refer to the new directory.

listdir()
FullForm:os.listdir(path)
Meaning: List Directory Contents
• This function returns a list of all files and folders in the specified directory.
• If no path is given, it lists the contents of the current working directory.

exists()
FullForm:os.path.exists(path)
Meaning: Check if Path Exists
• This function returns True if the given file or folder exists, otherwise False.
• It is used to avoid errors before trying to access, delete, or create files/directories.

Example:-
import os
print("Current Directory:", os.getcwd()) # getcwd()
os.mkdir("new_folder") # mkdir()
os.chdir("new_folder") # chdir()
print("Changed Directory:", os.getcwd())
print("Files:", os.listdir(".")) # listdir()
print("Folder Exists:", os.path.exists("new_folder")) # exists()

3. How to Create User-Defined Exceptions and Raise Them Manually?


Ans:-
User-Defined Exceptions is also called Custom Exceptions.To define a custom exception in
Python, you need to create a new class that inherits from the built-in Exception class or one
of its subclasses.
Custom exceptions are useful in the following scenarios:
1. Clarity: They provide clear, specific error messages that are relevant to your
application.
2. Granularity: They allow for more fine-grained error handling, making it easier to
pinpoint and address specific issues.
3. Reusability: They can be reused across different parts of your application or even in
different projects.
4. Use of read(), readline(), and readlines() in Python's File Handling
Ans:-
1. read()
Purpose: Reads the entire content of the file as a single string.
Features:
• Reads the whole file at once.
• Returns a single string, including \n for line breaks.
• Can take an optional size (number of characters to read).
When to use:
• When you need the complete file content as one block of text.

2. readline()
Purpose: Reads one line at a time from the file.
Features:
• Reads only the next line (up to \n).
• Each call to readline() moves the file pointer to the next line.
• Useful in loops for line-by-line reading.
When to use:
• When reading large files, to save memory.
• When processing file line-by-line (e.g., log files).

3. readlines()
Purpose: Reads all lines in the file and returns them as a list of strings.
Features:
• Each line becomes an element in the list.
• Includes newline characters (\n) at the end of each line.
• Easier to loop through lines with a for loop.
When to use:
• When you want to access all lines individually.
• Ideal for tasks like word count, parsing config files, etc.

Example :-
file = open("example.txt", "r")

print(file.read(10)) # Reads first 10 characters


print(file.readline()) # Reads one line
print(file.readlines()) # Reads all lines as a list

file.close()

5. General Syntax of try-except-finally Block


Ans:-
Syntax:-

try:
# Code that may cause an error
risky_code()
except ExceptionType as e:
# Handle the exception
print("An error occurred:", e)
finally:
# Code that always executes
print("This will always run.")

Example:

try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Enter a number.")
finally:
print("Execution Completed.")

6. Demonstrate the Following Errors with Programs


i) IOError (File Not Found Error) ii) AttributeError iii) KeyError

Ans:-
i) IOError / FileNotFoundError
📌 Definition:
• IOError (Input/Output Error) occurs when an input/output operation fails.
• In Python 3, FileNotFoundError is a subclass of IOError and is raised specifically
when a file or directory is not found.
This error occurs when a program tries to open or read a file that doesn’t exist in the specified
location.

ii) AttributeError
📌 Definition:
An AttributeError is raised when you try to access an attribute or method that does not exist
for a particular object.

• Using a method that is not defined for that type of object.


• Misspelling method names or applying a method to the wrong data type.

iii) KeyError
📌 Definition:
A KeyError occurs when a program tries to access a dictionary key that doesn’t exist.
• Attempting to retrieve the value of a key that is not present in the dictionary.
• No default value is provided using .get() or handling with in keyword.

You might also like