ValueError exception in Python code examples

What does ValueError mean in Python?

If a function in Python receives an argument that is of the correct type but has an inappropriate value, it raises a ValueError. This exception is used when the situation does not fall under a more specific exception like IndexError.

2. An example of a ValueError.

If you perform mathematical operations like taking the square root of a negative number, you will encounter a ValueError.

>>> import math
>>> 
>>> math.sqrt(-10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> 

Dealing with an Exception related to ValueError.

I will provide one alternative for paraphrasing the given sentence natively:
“Let me present a straightforward instance where a ValueError exception can be managed using a try-except block.”

import math

x = int(input('Please enter a positive number:\n'))

try:
    print(f'Square Root of {x} is {math.sqrt(x)}')
except ValueError as ve:
    print(f'You entered {x}, which is not a positive number.')

Here are the results of the program when different kinds of input are used.

Please enter a positive number:
16
Square Root of 16 is 4.0

Please enter a positive number:
-10
You entered -10, which is not a positive number.

Please enter a positive number:
abc
Traceback (most recent call last):
  File "/Users/scdev/Documents/PycharmProjects/hello-world/scdev/errors/valueerror_examples.py", line 11, in <module>
    x = int(input('Please enter a positive number:\n'))
ValueError: invalid literal for int() with base 10: 'abc'

To handle all possible ValueError scenarios, we can use a nested try-except block in our program that covers both the int() and math.sqrt() functions. The updated code snippet manages these situations effectively.

import math

try:
    x = int(input('Please enter a positive number:\n'))
    try:
        print(f'Square Root of {x} is {math.sqrt(x)}')
    except ValueError as ve:
        print(f'You entered {x}, which is not a positive number.')
except ValueError as ve:
    print('You are supposed to enter positive number.')

4. Throwing a ValueError within a function

Here’s an easy instance where we throw a ValueError when the input argument is of the right type but has an unsuitable value.

import math


def num_stats(x):
    if x is not int:
        raise TypeError('Work with Numbers Only')
    if x < 0:
        raise ValueError('Work with Positive Numbers Only')

    print(f'{x} square is {x * x}')
    print(f'{x} square root is {math.sqrt(x)}')

5. Citations

  • Python Exception Handling
  • ValueError Python Docs

 

More tutorials

How to include items to a list in Python(Opens in a new browser tab)

Set in Python(Opens in a new browser tab)

Basics of Graph Plotting – Comprehending the plot() Function in R(Opens in a new browser tab)

breakpoint function in Python(Opens in a new browser tab)

Spring MVC HandlerInterceptorAdapter and HandlerInterceptor.(Opens in a new browser tab)

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *