Use try/except.

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."
...
Answer from Matt Ball on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 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 · The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
🌐
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
Discussions

Python: if error raised I want to stay in script - Stack Overflow
I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare th... More on stackoverflow.com
🌐 stackoverflow.com
Python: else ValueError: (Specifically ValueError In This Case) - Stack Overflow
I have a question which is unrelated to my code. I'm just curious. Why is it that I (I don't know about you) can only use a ValueError with a try and except loop? for example: print("What is 1 + 1... More on stackoverflow.com
🌐 stackoverflow.com
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
except VS except valueError: what's the difference?
It's always better to handle errors that you expect so that you don't bypass ones you don't expect. Except without an error afterwards bypasses all errors. except ValueError will only bypass a ValueError and therefore is better error handling. If a SyntaxError happens, then it won't be bypassed. This is good because it may not be expected and therefore you would not want to propagate further More on reddit.com
🌐 r/learnpython
6
1
May 19, 2020
🌐
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....
🌐
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.
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
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. This may occur if the value is ...
Find elsewhere
🌐
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 raised when an object is assigned the right data type but the wrong value for a certain operation. Some of the most common scenarios where this can happen are: If the value is invalid for the operation.
🌐
Real Python
realpython.com › ref › builtin-exceptions › valueerror
ValueError | Python’s Built-in Exceptions – Real Python
Python · >>> user_input = "one" >>> try: ... number = int(user_input) ... except ValueError: ... print(f"Could not convert '{user_input}' to an integer.") ... Could not convert 'one' to an integer. If you’re writing a function that demands certain value constraints, you can raise ValueError to enforce them: Python ·
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.4 documentation
If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise. 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...
🌐
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.
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › valueError.html
Error Encyclopedia | Value Error
>>> a, b, c, d = [3, 4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 3 values to unpack · This returns a value error, because there are too few values on the right-hand side for Python to ‘unpack.’ When Python tries to assign ‘d’ to a value on the right-hand side, it is unable to find any matching value to ‘unpack’, and thus throws a ValueError.
🌐
Linux Hint
linuxhint.com › handling-value-error-exception-python
Handling the ValueError Exception in Python – Linux Hint
try: #Open the file for reading fh = open('sales.txt') #Define while loop to read file line by line while fh: #Convert the line into the integer value = int(fh.readline()) #Print the value print(value) except (ValueError, IOError): ''' Print the error message if the file is unable to read or the file contains any string data ''' print("ValueError or IOError has occurred.") ... The following output will appear after executing the above script. Here, the ValueError has been generated because the sales.txt file contains alphabetic characters at line number 6. Create a Python file with the following script that will take a number from the command-line argument value.
🌐
iO Flood
ioflood.com › blog › python-valueerror
[SOLVED] Python ValueError | Causes and Solutions
January 30, 2024 - A ValueError in Python is raised when a function receives an argument of the correct type but an inappropriate value. To handle it, you can use a try-except block to catch the error and handle it appropriately.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-valueerror-exceptions-in-python
How To Fix Valueerror Exceptions In Python - GeeksforGeeks
July 23, 2025 - Below, are the ways to solve the Valueerror Exceptions in Python ... Below, code attempts to convert a numeric value (`a`) and a non-numeric string (`b`) to floats using the `float()` function. A try-except block is used to catch a potential `ValueError` that may occur during the conversion of the non-numeric string. If such an error occurs, it prints a clear error message indicating the inability to convert the string to a float.
🌐
Medium
infotechdreamer.medium.com › valueerror-in-python-what-it-is-how-to-fix-63251108438c
ValueError in Python: What it is & How To Fix? | by Infotechdreamer | Medium
July 25, 2023 - A ValueError is a type of Python error that occurs when a function or operation receives an argument that has the right type but an inappropriate value. Here are some common examples of ValueErrors in Python: A function might expect an integer, ...
🌐
w3resource
w3resource.com › python-exercises › python-exception-handling-exercise-2.php
Python Program for valid integer input
July 9, 2025 - If the conversion fails and a ValueError exception is raised, the program jumps to the except block. In the except block, we catch the ValueError exception and print an error message indicating the input is invalid. ... Input an integer: abc Error: Invalid input, input a valid integer. Input value: None · Input an integer: 10.06 Error: Invalid input, input a valid integer. Input value: None ... Write a Python program that repeatedly prompts the user for input until a valid integer is entered, raising ValueError for invalid inputs.
🌐
Reddit
reddit.com › r/learnpython › what's the difference between a typeerror and valueerror?
r/learnpython on Reddit: What's the difference between a TypeError and ValueError?
September 21, 2022 -

In this example:

x = int(input("x: "))
print(f'x = {x}')

if the input is a string, a ValueError is raised. Why not a TypeError? An invalid data type is inputted after all.