0% found this document useful (0 votes)
14 views5 pages

Unit 4

The document discusses various directory methods in the Python OS module, including creating, removing, and listing directories, as well as changing and checking the current working directory. It also explains the use of the assert and raise keywords for exception handling, providing examples of how to handle exceptions like ValueError and ZeroDivisionError. Additionally, it demonstrates how to create custom exceptions in Python with a program that calculates the square root of a number while raising an exception for negative inputs.
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)
14 views5 pages

Unit 4

The document discusses various directory methods in the Python OS module, including creating, removing, and listing directories, as well as changing and checking the current working directory. It also explains the use of the assert and raise keywords for exception handling, providing examples of how to handle exceptions like ValueError and ZeroDivisionError. Additionally, it demonstrates how to create custom exceptions in Python with a program that calculates the square root of a number while raising an exception for negative inputs.
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/ 5

UNIT-IV

8 MARKS
33. Discuss various directory methods in OS module.
The OS module in Python provides a way to interact with the operating system, and one of
its key functionalities is managing directories. Here are various directory-related methods
provided by the os module:
1.os.mkdir(path[, mode])
Creates a new directory at the specified path.
Syntax:
os.mkdir(path, mode=0o777)
Creates a new directory at the specified path.
2. os.makedirs(path[, mode])
Creates intermediate directories in the path if they do not exist.
Syntax:
os.makedirs(path, mode=0o777)
3. os.rmdir(path)
Removes an empty directory.
Syntax:
os.rmdir(path)
4. os.removedirs(path)
Removes directories recursively, but only if they are empty.
Syntax:
os.removedirs(path)
5. os.listdir(path='.')
Returns a list of entries (files and directories) in the specified directory.
Syntax:
os.listdir(path='.')
6.os.chdir(path)
Changes the current working directory to the specified path.
Syntax:
os.chdir(path)
7. os.getcwd()
Returns the current working directory.
Syntax:
os.getcwd()
8. os.rename(src, dst)
Renames a file or directory from src to dst.
Syntax:
os.rename(src, dst)
9.os.path.isdir(path)
Checks if the given path is a directory.
Syntax:
os.path.isdir(path)
10.os.path.exists(path)
Checks if the specified path exists
Syntax:
os.path.exists(path)

34. Explain the utility of Assert and Raise keywords. Show how to handle
various exceptions with examples.
1. assert Keyword:
The assert keyword is used for debugging purposes in Python. It tests a
condition, and if the condition evaluates to False, it raises an AssertionError
exception with an optional message. It is mainly used to check if the code is
working as expected during development and testing.
Syntax:
assert condition, "Error message"
Example:
x = 10
assert x > 5, "x should be greater than 5"
assert x < 5, "x should be less than 5"

2. raise Keyword:
The raise keyword is used to manually raise exceptions in Python. You can use it to throw
exceptions when a certain condition is met in your code. It is commonly used for error
handling and custom exceptions.
Syntax:
raise ExceptionType("Error message")
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
else:
print("Age is valid.")
try:
age = int(input("Enter your age: "))
check_age(age)
except ValueError as e:
print(f"Error: {e}")
OUTPUT:
Enter your age: 20
Age is valid.

Handling various exceptions with an example.


def divide_numbers():
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError as e:
print(f"Error: Cannot divide by zero. {e}")
except ValueError as e:
print(f"Error: Invalid input. Please enter a valid integer. {e}")
else:
print("Division was successful.")
finally:
print("Execution completed.")
divide_numbers()
OUTPUT:
Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero. division by zero
Execution completed.

35. How can you create your own exceptions in Python? Write a program to
print the square root of a number, raise an exception if number is negative.
In Python, you can create your own exceptions by defining a custom exception class. This
class should inherit from the built-in Exception class (or one of its subclasses). You can then
use the raise keyword to raise your custom exception when needed.
Steps to Create Your Own Exception:
1. Define a Custom Exception Class: Inherit from the built-in Exception class.
2. Raise the Custom Exception: Use the raise keyword to throw the exception when a
specific condition is met.

Program to Print Square Root and Raise Exception for Negative Numbers:

import math

class NegativeNumberError(Exception):

"""Exception raised when a negative number is provided."""


pass

def calculate_square_root(number):

if number < 0:

raise NegativeNumberError("Cannot calculate the square root of a negative number.")

else:

return math.sqrt(number)

try:

num = float(input("Enter a number: "))

result = calculate_square_root(num)

print(f"The square root of {num} is {result}")

except NegativeNumberError as e:

print(f"Error: {e}")

except ValueError:

print("Error: Please enter a valid number.")

OUTPUT:
Enter a number: 16
The square root of 16.0 is 4.0

You might also like