In this article, we will learn about the statement ‘raise ValueError’.
We will try to understand what it means and when to use it with the help of examples. Without further ado, let’s begin!
What is ValueError?
To define ValueError in simple terms, it is an exception that is raised when an incorrect value is passed to a function. “Value” in “ValueError” refers to the value of the variable.
The ValueError exception is usually raised when a given function needs the value of the passed-in variable to satisfy certain conditions.
For example, consider the built-in int() function, its duty is to convert a string to an integer.
>>> a = "5"
>>> type(a)
<class 'str'>
>>> b = int(a)
>>> type(b)
<class 'int'>
Here as you can see
- variable ‘a’ is of type str or string
- it is passed into the int() function, and the output is stored in the variable ‘b’
- the variable ‘b’ is of type int or integer which contains the value 5
But now let’s say I pass in the string “five” instead of the string “5”
>>> int("five")
Traceback (most recent call last):
File "/usr/lib/python3.10/idlelib/run.py", line 578, in runcode
exec(code, self.locals)
File "<pyshell#1>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'five'
As you can see
- the built-in int() function does not know how to deal with the value “five”
- int() can only deal with strings with numbers inside and not alphabet
- hence it raises a ValueError.
The important point to note here is
Even though “5” and “five” are both strings, the value inside the second one is made up of alphabets instead of numbers, and hence the Value of the variable is wrong resulting in ValueError
embeddedinventor.com
If this short answer is not making much sense to you I suggest reading our comprehensive article about ValueError here.
ValueError: A Step By Step Troubleshooting Guide
In the above article, we have explained what ValueError is and how to troubleshoot it if you ever run into ValueError!
Now let’s get back to the topic of focus and learn what the code “raise ValueError” means!
What does “raise ValueError” mean?
In the following program, we are getting an input from the user to calculate the area of a rectangle.
As you might already know, length cannot be negative, so developers usually write code like shown below to avoid bad inputs.
def calc_area(length, breadth):
if (length < 0) or (breadth < 0):
raise ValueError ("Please enter postive integers! Length or breadth cannot be negative!")
else:
return length * breadth
When we run the function with valid inputs like this:
print(calc_area(10, 33))
We get the area with no problems:
330
But when we pass invalid inputs:
print(calc_area(-1, 33))
The interpreter raises the ValueError:
Traceback (most recent call last):
File "/home/main.py", line 7, in <module>
print(calc_area(-1, 33))
File "/home/main.py", line 3, in calc_area
raise ValueError ("Please enter postive integers! Length or breadth cannot be negative!")
ValueError: Please enter postive integers! Length of breadth cannot be negative!
This is not strictly confined to math problems though. Let’s look at a real-world “non-math” example where you might need to raise a ValueError!
def voting_eligibility(age, voter_id):
if age < 18:
raise ValueError("You are not eligible to vote.")
if len(str(id)) != 11:
raise ValueError("Your ID number is invalid.")
print(name + " you are eligible to vote, please proceed.")
# valid voter, will not raise an error
print(voting_eligibility("Yasmin", 32, 82019375738))
# invalid voter, raises an error. Age is below the required age.
print(voting_eligibility("John", 17, 94720191837))
# invalid voter, raises an error. Invalid ID.
print(voting_eligibility("Yasmin", 27, 8921))
The above is a real-life example of utilizing the ValueError. Let’s break it down:
- We first define a function voting_eligibility() that takes in three arguments name, age, voter_id
- The function determines if the user is eligible to vote or not using two of the arguments age, voter_id
- If the age of the user seems to be less than 18, it is an invalid input, and hence a ValueError is raised
- The same is done after checking if the voter ID is correct and valid or not by checking the length of the ID.
For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions in Python!
7 Most Common In-Built Exceptions in Python!
If you are a visual learner here is a YouTube video that we made on that same topic!
And with that, I will end this article.
Congratulations on making it to the end of the article, not many have the perseverance to do so!
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Related Articles
ValueError: A Step By Step Troubleshooting Guide
Python: Manually throw/raise an Exception using the “raise” statement
Python: “raise exception from e” Meaning Explained!
Exceptions in Python: Explained for Beginners!
Thanks to Namazi Jamal for his contributions in writing this article!