python qb
python qb
Ans:-
import matplotlib.pyplot as plt
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)
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)
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}")
Example:-
Example:
Step 1: Create my_module.py
def greet(name):
return f"Hello, {name}!"
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
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.
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()
def display(self):
print("Name:", self.name)
print("Age:", self.age)
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
# 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)
Output:-
Name: Alice
Age: 20
Student ID: S12345
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.
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.
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")
c = Child()
c.father_traits()
c.mother_traits()
c.child_traits()
output:-
Father: Hardworking
Mother: Caring
Child: Inherits both traits
Chapter 6 :
Syntax of tell():-
file_object.tell()
file_object.seek(offset, whence)
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()
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")
file.close()
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.")
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.
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.