Tutorial

Python ValueError Exception Handling Examples

Published on August 3, 2022
author

Pankaj

Python ValueError Exception Handling Examples

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 "<stdin>", line 1, in <module>
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 <module>
    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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 25, 2020

Wow!! You codes are simple hence easy to understand… they are really fun to type…thanks

- Jemoh

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.