What is typeerror and valueerror in python?

What is typeerror and valueerror in python?

Errors detected during the Python program execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in your programs. Errors cannot be handled, while exceptions in Python can be handled at the run time.

Exception handling makes your code more hale and helps anticipate potential failures that would cause your program to stop in an uncontrolled manner.

Errors can be defined as the following types:

  1. Syntax Error
  2. Out of Memory Error
  3. Recursion Error
  4. Exceptions

An exception object is created when a Python script raises an exception. Let’s see the ValueError exception.

The ValueError exception in Python is raised when the method receives the argument of the correct data type but an inappropriate value. The associated value is a string giving details about the data type mismatch.

The TypeError exception in Python may be raised by user code to indicate that an attempted operation on an object is not supported and is not meant to be.

Let’s see the ValueError Exception example.

import math

math.sqrt(-10)

Output

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/database/app.py", line 3, in 
    math.sqrt(-10)
ValueError: math domain error

As you can see that we got the ValueError: math domain error.

How to resolve ValueError Exception in Python

To resolve the ValueError exception, use the try-except block. The try block lets you test a block of code for errors. The except block lets you handle the error.

import math

data = 64

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

Output

Square Root of 64 is 8.0

Now, let’s assign the negative value to the data variable and see the output.

import math

data = -64

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

Output

You entered -64, which is not a positive number

You can see that our program has raised the ValueError and executed the except block.

Our program can raise ValueError in int() and math.sqrt() functions. So, we can create a nested try-except block to handle both of them.

Conclusion

Passing arguments of the wrong data type should result in the TypeError, but passing arguments with a wrong value should result in the ValueError.

That is it for the ValueError exception in Python.

See also

ValueError: Math Domain Error in Python

No Such File Or Directory Error in Python

Python cv2 module not found error

1. What is Python ValueError?

Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.

2. ValueError Example

You will get ValueError with mathematical operations, such as square root of a negative number.

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

3. Handling ValueError Exception

Here is a simple example to handle ValueError exception using 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 is the output of the program with different types of input.

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/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/valueerror_examples.py", line 11, in 
    x = int(input('Please enter a positive number:\n'))
ValueError: invalid literal for int() with base 10: 'abc'

Our program can raise ValueError in int() and math.sqrt() functions. So, we can create a nested try-except block to handle both of them. Here is the updated snippet to take care of all the ValueError scenarios.

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. Raising ValueError in a function

Here is a simple example where we are raising ValueError for input argument of correct type but inappropriate 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. References

  • Python Exception Handling
  • ValueError Python Docs

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

What is the difference between TypeError and ValueError in Python?

A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError occurs when a built-in 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 .

What is a ValueError in Python?

The Python ValueError is an exception that occurs when a function receives an argument of the correct data type but an inappropriate value. This error usually occurs in mathematical operations that require a certain kind of value.

How do I fix Python ValueError?

To resolve the ValueError exception, use the try-except block. The try block lets you test a block of code for errors. The except block lets you handle the error.

What is TypeError in Python?

TypeError is a kind of error that python generates. We are trying to perform the operation of the wrong type of object. For example, if we are trying to do the square root of a number but we are passing a list instead of int, then TypeError will be generated by the python.