@Liam Hayes (https://teamtreehouse.com/liamhayes) Hi! I have a note about @Steven Parker (https://teamtreehouse.com/stevenparker)'s example (especially the second one). When I was trying to wrap my head around this, I could not for the life of me understand why the built-in function for changing something to an int would give a ValueError with a string as opposed to a TypeError. Surely, it's expecting a number, right? Well, no. It isn't. The int() function takes either a number or a string. It can convert the string "21" to the integer 21, but it can't convert "dog" to a number. Thus, it's getting the right type, but it's still not a value that it can convert. This is when we get the ValueError. It's of the right type, but the value is such that it still can't be done. That being said, if we tried to send in something that was neither a string nor a number, it would have generated a TypeError as it is of the wrong type. Hope this helps! :sparkles: edited for additional note In your own custom made functions, you can pass in whatever you want, although ideally, you know what you're passing in. This is not true of built-in functions in Python. When in doubt, check the documentation for the function in question. Answer from Jennifer Nordell on teamtreehouse.com
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.4 documentation
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
When a user calls a function with an invalid value but a valid argument, Python raises ValueError. Even though the value is the correct argument, it typically happens in mathematical processes that call for a specific kind of value. When an object is given the incorrect value, the Python ValueError is raised.
Discussions

In Python, what's the difference between a Type Error and a Value Error?
This is not true of built-in functions in Python. When in doubt, check the documentation for the function in question. Loading banner... Full Stack JavaScript Techdegree Student 13,116 Points ... A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
October 24, 2017
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
Learn what Python ValueError means, why it occurs, and how to fix it with practical examples, best practices, and real-world use cases. More on accuweb.cloud
🌐 accuweb.cloud
1
January 15, 2024
python - How to raise a ValueError? - Stack Overflow
I have this code which finds the largest index of a specific character in a string, however I would like it to raise a ValueError when the specified character does not occur in a string. So someth... More on stackoverflow.com
🌐 stackoverflow.com
Calling "if" statement on errors (TypeError, ValueError, SyntaxError...)
I’m creating an operating system within python. I’ve created the init system, the workflows, the plans… The only thing i need to do now is to make a valid shell I want to integrate Bash and Python together, so I’d need a way to have an “if” statement for example: text = input("PySH> ... More on discuss.python.org
🌐 discuss.python.org
5
0
April 20, 2021
🌐
W3Schools
w3schools.com › python › ref_exception_valueerror.asp
Python ValueError Exception
Python Examples Python Compiler ... Python Certificate Python Training ... The ValueError exception occurs if a function receives a value of wrong type....
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-valueerror-exceptions-in-python
How To Fix Valueerror Exceptions In Python - GeeksforGeeks
July 23, 2025 - In conclusion, resolving ValueError exceptions in Python involves meticulous examination of input data and ensuring compatibility with the expected format. Employing proper validation techniques, such as try-except blocks and conditional statements, can help preemptively catch and handle potential issues.
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › valueError.html
Error Encyclopedia | Value Error
In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.
🌐
Real Python
realpython.com › ref › builtin-exceptions › valueerror
ValueError | Python’s Built-in Exceptions – Real Python
Occurs when a function or operation receives an argument that has the right type but an inappropriate value.
🌐
Educative
educative.io › answers › what-is-valueerror-in-python
What is ValueError in Python?
ValueError in Python is raised when a user gives an invalid value to a function but is of a valid argument.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-valueerror-exception-handling-examples
Python ValueError Exception Handling: Examples & Fixes | DigitalOcean
August 3, 2022 - Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
Top answer
1 of 2
8
@Liam Hayes (https://teamtreehouse.com/liamhayes) Hi! I have a note about @Steven Parker (https://teamtreehouse.com/stevenparker)'s example (especially the second one). When I was trying to wrap my head around this, I could not for the life of me understand why the built-in function for changing something to an int would give a ValueError with a string as opposed to a TypeError. Surely, it's expecting a number, right? Well, no. It isn't. The int() function takes either a number or a string. It can convert the string "21" to the integer 21, but it can't convert "dog" to a number. Thus, it's getting the right type, but it's still not a value that it can convert. This is when we get the ValueError. It's of the right type, but the value is such that it still can't be done. That being said, if we tried to send in something that was neither a string nor a number, it would have generated a TypeError as it is of the wrong type. Hope this helps! :sparkles: edited for additional note In your own custom made functions, you can pass in whatever you want, although ideally, you know what you're passing in. This is not true of built-in functions in Python. When in doubt, check the documentation for the function in question.
2 of 2
0
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. Examples: passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. For more details, see the Exceptions page (https://docs.python.org/3/library/exceptions.html) of the Python documentation.
🌐
iO Flood
ioflood.com › blog › python-valueerror
[SOLVED] Python ValueError | Causes and Solutions
January 30, 2024 - Think of a ValueError as a traffic signal in your code – it stops the flow of your program when it encounters an inappropriate value. It’s a mechanism Python uses to ensure that the functions and operations in your code are receiving the right kind of values they expect.
🌐
Rollbar
rollbar.com › home › how to fix valueerror exceptions in python
How to Fix ValueError Exceptions in Python | Rollbar
June 24, 2024 - The Python ValueError is an exception that occurs when a function receives an argument of the correct data type but an inappropriate value.
🌐
Initial Commit
initialcommit.com › blog › valueerror-python
Python ValueError Exception – How to Identify & Handle
January 9, 2023 - ... exception ValueError: 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.
🌐
Accuweb
accuweb.cloud › home › explain python valueerror exception handling (with real examples & best practices)
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
January 15, 2024 - Python ValueError is raised when a function receives a value of the correct type but an inappropriate or invalid value.
Top answer
1 of 4
190

raise ValueError('could not find %c in %s' % (ch,str))

2 of 4
30

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

def contains(char_string, char):
    largest_index = -1
    for i, ch in enumerate(char_string):
        if ch == char:
            largest_index = i
    if largest_index > -1:  # any found?
        return largest_index  # return index of last one
    else:
        raise ValueError('could not find {!r} in {!r}'.format(char, char_string))

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "how-to-raise-a-valueerror.py", line 15, in <module>
    print(contains('bababa', 'k'))
  File "how-to-raise-a-valueerror.py", line 12, in contains
    raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with a quick unit test:

def contains(char_string, char):
    #  Ending - 1 adjusts returned index to account for searching in reverse.
    return len(char_string) - char_string[::-1].index(char) - 1

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "better-way-to-raise-a-valueerror.py", line 9, in <module>
    print(contains('bababa', 'k'))
  File "better-way-to-raise-a-valueerror", line 6, in contains
    return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found
🌐
LabEx
labex.io › tutorials › python-how-to-manage-valueerror-in-python-417443
How to manage ValueError in Python | LabEx
Python is a powerful and versatile programming language, but like any language, it comes with its own set of challenges. One such challenge is the ValueError exception, which can occur when a function receives an argument of the correct type but an inappropriate value.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › python valueerror
Python ValueError | How to Avoid ValueError in Python with Examples
May 13, 2024 - In Python, the worth is data that is put away inside a specific item. To experience a ValueError in Python implies that is an issue with the substance of the article you attempted to allocate the incentive to. This is not to be mistaken for types in Python. Hence, Python ValueError is raised when capacity gets a contention of the right kind; however, it an unseemly worth it.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Python.org
discuss.python.org › python help
Calling "if" statement on errors (TypeError, ValueError, SyntaxError...) - Python Help - Discussions on Python.org
I’m creating an operating system within python. I’ve created the init system, the workflows, the plans… The only thing i need to do now is to make a valid shell I want to integrate Bash and Python together, so I’d need a way to have an “if” statement for example: text = input("PySH> ") if input == SyntaxError: # execute this That’s my crude explanation of what my problem is
Published   April 20, 2021
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error:", err) except ValueError: print("Could not convert data to an integer.") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise
🌐
MangoHost
mangohost.net › mangohost blog › python valueerror – exception handling with examples
Python ValueError – Exception Handling With Examples
August 3, 2025 - Python ValueError is one of the most frequently encountered exceptions in Python programming, occurring when a function receives an argument with the correct type but an inappropriate value.
🌐
Scaler
scaler.com › home › topics › python valueerror
Python ValueError - Scaler Topics
December 15, 2022 - As discussed above, Value Error in python occurs when a correct argument type but an incorrect value is supplied to a function. There are many reasons you might see the Python ValueError pop-ups and these are mentioned below: