Python ValueError Exception with Examples

Python | ValueError Exception: In this tutorial, we will learn about the ValueError Exception in Python with the help of examples. By IncludeHelp Last updated : September 19, 2023

Exception Handling in Python is the method using which exceptions are handled in python. Exceptions are errors that change the normal flow of a program.

Python programming language provides programmers a huge number of exception handler libraries that help them to handle different types of exceptions.

One such exception is ValueError exception, let's understand it in detail.

Python ValueError Exception

ValueError Exception in python occurs when the variable is fed with wrong value or the value which is out of the expected bound. This is similar to type error which looks for wrong type instead.

Python ValueError Exception Example

In the below example, we have a Python list, and removing the elements from it using the list.remove() method. If the specific element does not exist in the list then the method will return a ValueError.

# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]

# printing the list
print("x before remove operations...")
print("x: ", x)

x.remove(10)   # will remove 10
x.remove(70)   # will remove 70

# printing the list
print("x after remove operations...")
print("x: ", x)

# removing an element that doesn't exist
# in the list...
x.remove(100) # will generate error

Output

x before remove operations...
x:  [10, 20, 30, 40, 50, 60, 70]
x after remove operations...
x:  [20, 30, 40, 50, 60]
Traceback (most recent call last):
  File "/home/main.py", line 17, in <module>
    x.remove(100) # will generate error
ValueError: list.remove(x): x not in list

Python ValueError Exception with Try Except

Here is another example that will help you to learn more about it, suppose you are taking marks of the student as input from users. If the user enters strings it is treated as a typeError but if the user enters a value greater than 100, it is treated as a valueError.

Example

# Python program to illustrate ValueError Exception 

# Try Block Starts
try:
    # Taking input from the user ... 
    # The input strictly needs to be an integer value...
    num1 = int(input("Enter number 1 : "))
    num2 = int(input("Enter number 2 : "))

    # Adding the two numbers and printing their result.
    numSum = num1 + num2
    print("The sum of the two numbers is ",numSum)
    
# except block 
except ValueError as ex:
    print(ex)

Output

Run 1: 
Enter number 1 : 10
Enter number 2 : 20
The sum of the two numbers is  30

Run 2: 
Enter number 1 : 32.2
invalid literal for int() with base 10: '32.2'

Explanation

In the above code, we have created two variables num1 and num2 and taken user input for their values. Both the values entered need to be integer values only. And then we have printed their sum. The exception we have handled here is valueError but we have not put any upper limit to the value of the integer to be entered, and by default you can create an integer as big as you want in python. And hence, if we enter a non-integer value the ValueError exception returns the exception statement.

Python ValueError Exception while Reading the Invalid Value

# Python program to illustrate valueError Exception 
import math

# Try Block Starts
try:
    # Taking input from the user ... 
    # The input needs to be a positive integer value...
    num1 = int(input("Enter number 1 : "))
    
    # finding the square root of the number. 
    # So the number cannot be negative.
    squareRoot = math.sqrt(num1)
    print("The Square root of the number is ",squareRoot)
    
# except block 
except ValueError as ex:
    print(ex)

Output

Run 1:
Enter number 1 : 4
The Square root of the number is  2.0

Run 2:
Enter number 1 : 12.3
invalid literal for int() with base 10: '12.3'

Python exception handling programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.