Python ValueError Exact Solution with Examples

In this tutorial, we will discuss on how to fix valueerror in Python with the help of examples.

Introduction

Errors that occur during Python program execution are called exceptions, one of which is ValueError. Python ValueError is raised when a user gives a correct data type but an inappropriate value. It usually happens in math operations that need a certain kind of value, even if that value is the right argument.

What is Python ValueError?

Python throws a ValueError when a function receives an argument with the right type but the wrong value. Also, a precise exception such as IndexError shouldn’t be used to describe the situation.

Also read: Python Make Directory with Examples

The exception ValueError documentation provides further information:

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

Python Documentation

ValueError Example

If you do a mathematical operation like taking the square root of a negative number, you will get a ValueError.

import math
math.sqrt(-50)

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
ValueError: math domain error

Handling ValueError Exception

Here is a simple example of how to use a try-except block to handle a ValueError error.

import math

x = int(input("Enter a number: "))

try:
    print(f"The square Root of {x} is {math.sqrt(x)}")
except ValueError as ve:
    print(f"You entered {x}, which is a negative number.")

Output:

# When you enter a possitive number
Enter a number: 9
The square Root of 9 is 3.0

# When you enter a negative number
Enter a number: -9
You entered -9, which is a negative number.

# When you enter a letter not a number
Enter a number: abc
Traceback (most recent call last):
  File "main.py", line 3, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

Int() and math.sqrt() functions in our program can throw ValueError. So, we can handle both of them with a nested try-except block. Here is the updated snippet that takes care of all the ValueError cases.

import math

try:
    x = int(input("Enter a number: "))
    try:
        print(f"The square Root of {x} is {math.sqrt(x)}")
    except ValueError as ve:
        print(f"You entered {x}, which is a negative number.")
except ValueError as ve:
    print('You must enter a positive number.')

Raising ValueError in a Function

Here’s a simple example of throwing a ValueError when an argument’s type is correct, but its value is wrong.

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)}')

How do I fix Python ValueError?

To fix Python ValueError use a try-except block. The try block lets you test code for errors and the except block lets you handle errors.

Example:

import math

x = 16

try:
    print(f"The square Root of {x} is {math.sqrt(x)}")
except ValueError as v:
    print(f"You entered {x}, which is a negative number")

Output:

The square Root of 16 is 4.0

Now, let’s give the data variable a negative value and look at what happens.

import math

x = -16

try:
    print(f"The square Root of {x} is {math.sqrt(x)}")
except ValueError as v:
    print(f"You entered {x}, which is a negative number")

Output:

You entered -16, which is a negative number

The ValueError has been thrown by our program, and the except block has been run.

In the int() and math.sqrt() functions of our program, we can get a ValueError. So, we can handle both of them by making a try-except block inside another one.

What causes a ValueError in Python?

The causes of ValueError are the following:

1. Converting a string into a number.

int = ("Python for FREE!")

2. If you attempt to remove a component that does not appear on the list, an error will occur.

x = 10
list = [2,4,6,8]
list.remove(x)

3. If you attempt to “unpack” more values than you actually have, you will receive an error message.

x, y, z = [1, 2, 3]

4. In the event that you enter a negative value into the square root.

import math
x = -9
print({math.sqrt(x)})

How do you avoid ValueError?

To avoid the ValueError, make sure the number of factors and the number of rundown components match. You can also use a loop to iterate through the components and print them individually.

Another way to avoid ValueError is to use a try-except block. This will allow you to try running a code, and if it produces any type of error message, the except block will handle it.

Summary

To handle a ValueError in Python, use a block that has both a ‘try‘ and a ‘except‘ statement. This tutorial uses multiple examples to show how to properly use this exception.

Leave a Comment