KnowledgeBoat Logo
LoginJOIN NOW

Computer Science

You have learnt how to use math module in Class XI. Write a code where you use the wrong number of arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError exception.

Python Exception Handling

4 Likes

Answer

Note — The TypeError occurs when an incorrect number of arguments is provided for a function, while the ValueError occurs when the number of arguments are correct but they contain inappropriate values. Hence, in the following code TypeError is raised due to providing an incorrect number of arguments to the math.sqrt() and math.pow() function and it is handled using except.

import math

try:
    result = math.pow(2, 3, 4, 5)  # pow() expects 2 arguments,
                                   # but 4 are provided
except TypeError:
    print("TypeError occurred with math.pow()")
else:
    print("Result:", result)

try:
    result = math.sqrt(9, 2)  # sqrt() expects 1 argument,
                              # but 2 are provided
except TypeError:
    print("TypeError occurred with math.sqrt()")
else:
    print("Result:", result)
Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()

Answered By

2 Likes


Related Questions