Chapter 4 Modules ,Working with files, Exception handling

  - What is regEx? give example.

import re

# Regular Expression Example

pattern = re.compile(r'\b\d{3}-\d{2}-\d{4}\b')  # Matches social security numbers

text = "John's SSN is 123-45-6789."

match = pattern.search(text)


if match:

    print("SSN found:", match.group())

else:

    print("No SSN found.")


- What is user defined Module? Give example.

# User-Defined Module Example

# Save this code in a file named mymodule.py

def greet(name):

    return f"Hello, {name}!"


# In another script, you can use this module

import mymodule


message = mymodule.greet("Alice")

print(message)


 -What is the use of seek( ) & tell ( ) functions?

seek(offset, whence): Moves the file cursor to the specified offset position, relative to whence (0 for the beginning, 1 for the current position, and 2 for the end).

tell(): Returns the current position of the file cursor.


Write a short note on exception handling.

Exception Handling:

Exception handling in Python allows you to deal with errors or exceptions that may occur during the execution of a program. It involves the use of try, except, else, and finally blocks.

try:

    result = 10 / 0

except ZeroDivisionError:

    print("Cannot divide by zero!")

else:

    print(f"Result: {result}")

finally:

    print("This block always executes.")



 -What is a module? What is package? Explain with example.

Module: A module in Python is a file containing Python definitions and statements. It allows you to logically organize your Python code. For example:

# mymodule.py

def greet(name):

    return f"Hello, {name}!"

# main.py

import mymodule


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

Package: A package is a way of organizing related modules into a single directory hierarchy. It helps in organizing the code and avoids naming conflicts. A package contains an __init__.py file and can have subpackages. Example:


mypackage/

├── __init__.py

├── module1.py

└── module2.py


 Explain any 2 functions in time module.

Answer: 

a. time.time()

Returns the current time in seconds since the epoch.

import time current_time = time.time() print(current_time)

1642635122.547345

(since epoch is jan 1 1970)


b. time.sleep()

Suspends the execution for a specified number of seconds.

import time time.sleep(2) print("Resumed after 2 seconds.")



 --What are the types of file in Python?

Answer: 

  • Text Files ('t' or default mode): Human-readable files.
  • Binary Files ('b' mode): Non-human-readable files (e.g., images, audio).

- Write the use of seek & tell function.

Answer: seek(offset, whence): Changes the file's current position.

with open('example.txt', 'r') as file: file.seek(5) data = file.read(10)

tell(): Returns the current position of the file cursor.
with open('example.txt', 'r') as file: position = file.tell()

# Writing to a file with open('example.txt', 'w') as file: file.write("Hello, World!") # Reading from the file using seek and tell with open('example.txt', 'r') as file: file.seek(3) # Move to the 4th character (zero-based indexing) data = file.read(5) # Read 5 characters position = file.tell() # Get the current position

print("Read data:", data) print("Current position:", position)

Output: Read data: lo, W Current position: 8


- How to handle exception in Python?

Answer: In Python, you can handle exceptions using a try-except block.

  • he try block contains the code that might raise an exception.
  • The except block catches and handles the specified exception (or a base class like Exception to catch all exceptions).
  • The else block is optional and contains code to execute if no exception occurred in the try block.
  • The finally block is optional and contains code that will be executed whether an exception occurred or not. It's useful for cleanup operations.
try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
    print(f"Error: {e}")
else:
    print("This will be printed if there is no exception.")
finally:
    print("This will be executed no matter what.")

Output:
Error: division by zero This will be executed no matter what.


-Explain any 2 metacharacters used in regular expression.

Answer: 

1. . (Dot):

  • Matches any single character (except newline).
  • import re pattern = r"gr.y" # Matches 'gray', 'green', etc. text = "The gray cat is on the green mat." result = re.findall(pattern, text) print(result)

  • Output:
    ['gray', 'green']

2. * (Asterisk):

  • Matches zero or more occurrences of the preceding character or group.
  • import re pattern = r"ab*c" # Matches 'ac', 'abc', 'abbc', 'abbbc', etc. text = "ac abc abbc abbbc abb" result = re.findall(pattern, text) print(result)

Output:
['ac', 'abc', 'abbc', 'abbbc']