0% found this document useful (0 votes)
13 views7 pages

PWP Ut

The document covers various fundamental concepts in Python, including file modes, the from...import statement, classes, packages, and user-defined functions. It explains modules, the reduce() function, file handling with open() and close() methods, and creating user-defined exceptions. Additionally, it briefly mentions the differences between method overloading and method overriding.

Uploaded by

milindnagare13
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)
13 views7 pages

PWP Ut

The document covers various fundamental concepts in Python, including file modes, the from...import statement, classes, packages, and user-defined functions. It explains modules, the reduce() function, file handling with open() and close() methods, and creating user-defined exceptions. Additionally, it briefly mentions the differences between method overloading and method overriding.

Uploaded by

milindnagare13
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/ 7

2 MARKS

Q1. List four file modes in Python.

Ans:
In Python, file modes determine how a file is opened and what operations can be performed on it. The four
common file modes are:

1. 'r' – Read mode:


Opens the file for reading. If the file does not exist, Python raises a FileNotFoundError. This is
the default mode used with open().
2. 'w' – Write mode:
Opens the file for writing. If the file already exists, its contents will be erased. If the file does not
exist, it creates a new one.
3. 'a' – Append mode:
Opens the file for writing, but does not erase existing data. New data is added at the end of the file. If
the file doesn’t exist, it is created.
4. 'b' – Binary mode:
Used to read or write binary files (like images, audio, etc.). It must be combined with other modes
like rb (read binary) or wb (write binary).

These modes can be combined (e.g., 'rb', 'wb', 'r+') to support different read/write/binary
combinations.

Q2. Explain the from...import statement.

Ans:
The from...import statement in Python is used to import specific attributes (like functions, classes, or
variables) from a module.
This is helpful when you don't want to import the whole module or when you want to directly use an item
without prefixing it with the module name.

Syntax:

from module_name import item_name

You can also import multiple items like this:

from math import sqrt, pi

Example:

from math import sqrt


print(sqrt(49)) # Output: 7.0

This improves readability and avoids writing math.sqrt() every time.

Q3. Define a class.


Ans:
A class in Python is a user-defined blueprint or prototype from which objects are created. It encapsulates
data (attributes) and functionality (methods) into one single unit.

Classes are the foundation of object-oriented programming in Python and support concepts like inheritance,
polymorphism, and encapsulation.

Syntax:

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

def display(self):
print("Student name:", self.name)

Here, Student is a class, and __init__() is the constructor method used to initialize the object.

Q4. Define a package.

Ans:
A package is a collection of related Python modules grouped together in a directory. It helps in organizing
large programs and makes code modular and manageable.

A package must contain an __init__.py file (can be empty), which tells Python that the directory should
be treated as a package.

Example structure of a package:

myapp/
├── __init__.py
├── student.py
└── teacher.py

To use a module from a package:

from myapp import student


student.function_name()

Packages can be nested to create sub-packages, enhancing code reusability.

Q5. Describe user-defined functions in Python.

Ans:
A user-defined function is a block of reusable code created by the programmer to perform a specific task.
Functions help reduce redundancy and break large programs into smaller, manageable parts. They improve
code clarity and reuse.

Functions in Python are defined using the def keyword.

Syntax:
def function_name(parameters):
# function body
return value

Example:

def add(a, b):


return a + b

print(add(3, 5)) # Output: 8

User-defined functions can take arguments, return values, and even call other functions.

4 MARKS

Q1. Define a module in Python. How to create and use it?

Ans:
A module in Python is a file containing Python definitions and statements. The filename of the module should have a
.py extension. Modules are used to break large programs into smaller, manageable, and organized files.
Modules improve code reusability, maintainability, and modular programming by allowing developers to reuse
functions, classes, and variables across multiple programs.

Creating a Module:

You can create a module by simply writing Python code in a file:

python
CopyEdit
# mymodule.py
def greet(name):
return f"Hello, {name}!"

This file now becomes a module named mymodule.

Using a Module:

You can import the module in another Python program using the import or from...import statement.

python
CopyEdit
import mymodule
print(mymodule.greet("Arpit"))

Or:

python
CopyEdit
from mymodule import greet
print(greet("Arpit"))
Advantages of Using Modules:

 Makes code modular and organized.


 Enhances code reusability.
 Avoids rewriting the same code again and again.
 Simplifies debugging and testing.

Python also provides a large number of built-in modules like math, os, random, datetime, etc.

Q2. Show the use of the reduce() function with an example.

Ans:
The reduce() function belongs to the functools module and is used to apply a specified function cumulatively
to the elements of a sequence, reducing it to a single value.

It performs operations like summing up a list of numbers, finding the product, etc., in a functional programming
style.

Syntax:
python
CopyEdit
from functools import reduce
reduce(function, sequence)

Here, the function must take two arguments. The reduce() function applies this function cumulatively to the
items of the sequence.

Example:
python
CopyEdit
from functools import reduce

def multiply(x, y):


return x * y

numbers = [2, 3, 4, 5]
result = reduce(multiply, numbers)
print(result) # Output: 120

Working:

Step-by-step:

 multiply(2, 3) → 6
 multiply(6, 4) → 24
 multiply(24, 5) → 120

Use Cases:

 Aggregating data (sum, product, max, etc.)


 Implementing custom reduction logic

It’s commonly used in data processing pipelines and when dealing with collections of data.
Q3. Explain open() and close() methods for opening and closing a file.

Ans:
Python provides built-in functions for file handling, which allows reading, writing, and modifying files on the system.

open() Function:

Used to open a file and return a corresponding file object.

Syntax:

python
CopyEdit
file = open(filename, mode)

 filename: Name (and path) of the file


 mode: File access mode (e.g., 'r', 'w', 'a', 'rb')

Common Modes:

 'r': Read (default)


 'w': Write (overwrites)
 'a': Append
 'rb', 'wb': Read/write binary

Example:

python
CopyEdit
f = open("data.txt", "r")

close() Function:

Closes the file and frees up system resources. Failing to close a file can lead to memory leaks or data loss.

Syntax:

python
CopyEdit
file.close()

Example:

python
CopyEdit
f = open("data.txt", "r")
data = f.read()
f.close()

Best Practice:

Use the with statement to handle files, which automatically closes the file:

python
CopyEdit
with open("data.txt", "r") as f:
content = f.read()

This approach is cleaner and safer.

Q4. Explain how to create a user-defined exception and raise it manually with an example.

Ans:
Python allows users to create custom (user-defined) exceptions to handle specific errors in a program that are not
covered by built-in exceptions.

Why Use User-Defined Exceptions?

 To create meaningful error messages.


 To handle errors that are specific to your application logic.
 To make the code more readable and maintainable.

Creating a User-Defined Exception:

1. Define a class that inherits from the built-in Exception class.


2. Use the raise statement to raise it when a specific condition is met.

Example:

python
CopyEdit
class AgeTooSmallError(Exception):
"""Exception raised when age is less than 18"""
pass

age = int(input("Enter your age: "))


if age < 18:
raise AgeTooSmallError("Age must be at least 18 to register.")
else:
print("You are eligible to register.")

Output:

If age entered is below 18, it raises AgeTooSmallError with a custom message.

This helps programmers to control program flow and prevent invalid operations.

Q5. Differentiate between Method Overloading and Method Overriding.

Ans:

You might also like