The SyntaxError in the second example comes from the fact, that else needs no condition. The first example is totally ok.

Still better, keep the try-block as short as possible:

print("What is 1 + 1?")
while True:
    try:
        UserInput = int(input(("Your answer here:"))
    except ValueError:
        print("That is not a number. Try again!")
    else:
        if UserInput == 2:
            print("Congratulations you are correct!")
            break
        else:
            print("That is incorrect. Try again!")
Answer from Daniel on Stack Overflow
🌐
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
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-valueerror-exception-handling-examples
Python ValueError Exception Handling: Examples & Fixes | DigitalOcean
August 3, 2022 - 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)}') Python Exception Handling ·
Discussions

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: 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
python - python3 ValueError value - Stack Overflow
Many languages support exceptions of course, but Python is one of the few where you will very frequently see code where the Exception case is actually a commonly-followed code path rather than one that only happens when something has gone really wrong. Here is an example of the correct use of a ValueError: def gen(selection): if ... More on stackoverflow.com
🌐 stackoverflow.com
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 documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
This must be either an exception ... will be implicitly instantiated by calling its constructor with no arguments: raise ValueError # shorthand ......
🌐
Real Python
realpython.com › ref › builtin-exceptions › valueerror
ValueError | Python’s Built-in Exceptions – Real Python
>>> def set_age(age): ... if age < 0: ... raise ValueError("Age can't be negative") ... print(f"Age is {age} years") >>> set_age(-5) Traceback (most recent call last): ... ValueError: Age can't be negative ...
🌐
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 - Let’s explore practical examples. try: num = int("abc") except ValueError as e: print("An error occurred:", e) Output: An error occurred: invalid literal for int() with base 10: 'abc'Copy ... try: age = int(input("Enter your age: ")) except ...
🌐
W3Schools
w3schools.com › python › ref_exception_valueerror.asp
Python ValueError Exception
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The ValueError exception occurs if a function receives a value of wrong type.
Find elsewhere
🌐
Educative
educative.io › answers › what-is-valueerror-in-python
What is ValueError in Python?
import math try: print(math.sqrt(-1)) except ValueError: print('You can not get take the square root of a negative number ')
🌐
Rollbar
rollbar.com › home › how to fix valueerror exceptions in python
How to Fix ValueError Exceptions in Python | Rollbar
June 24, 2024 - In the above example, the list myList containing 5 values is attempted to be unpacked and assigned to 3 variables. Since the number of values exceed the number of available variables, running the above code raises a ValueError: Traceback (most ...
Top answer
1 of 1
3

I think you misunderstand what ValueError (and in general, an Exception) is.

Exceptions are a way for a method to signal to its caller that some critical error condition has been encountered that would prevent that method from executing as intended. Python's try-except-finally control structure provides a way for the caller to detect those error conditions and react accordingly.

ValueError is a standard Exception raised by various methods that perform range-checking of some kind to signal that a value provided to the method fell outside the valid range. In other words, it's a universal way of signaling that error condition. ValueError by itself doesn't do any kind of checking. There are many other standard Exceptions like this; KeyError signifies that you tried to access a key in a mapping structure (like a dict or set) that didn't exist, IndexError means you tried to index into a list-like structure to an invalid location, etc. None of them actually do anything special in and of themselves, they're simply a way of directly specifying exactly what kind of problem was encountered by the called method.

Exceptions go hand in hand with the idiom in python that it is generally considered 'easier to ask forgiveness than permission'. Many languages support exceptions of course, but Python is one of the few where you will very frequently see code where the Exception case is actually a commonly-followed code path rather than one that only happens when something has gone really wrong.

Here is an example of the correct use of a ValueError:

def gen(selection):
    if imode == 0:
        # do EOS stuff here
    elif imode == 1:
        # do S2 stuff here
    else:
        raise ValueError("Please Select An Option Between 0-1")

def selector():
    while True:
        try:
            gen(int(input("Generate for EOS(0) or S2(1)")))
            break
        except ValueError as e: # This will actually satisfy two cases; If the user entered not a number, in which case int() raises, or if they entered a number out of bounds, in which chase gen() raises.
            print(e) 

Note there are probably much more direct ways to do what you want, but this is just serving as an example of how to correctly use a ValueError.

🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › valueError.html
Error Encyclopedia | Value Error
In this example, we define a variable ‘myVar’ to have the value 5. We then try to remove this value from a list that doesn’t contain that value. Because 5 is not in the list, we cannot remove it, and Python returns a value error. Additionally, you can also raise a ValueError in Python if you ...
🌐
iO Flood
ioflood.com › blog › python-valueerror
[SOLVED] Python ValueError | Causes and Solutions
January 30, 2024 - # Hierarchy of exceptions in Python BaseException | +-- Exception | +-- ValueError · This hierarchy is important because when you catch an exception, you also catch all of its subclasses. For example, if you catch Exception, you’ll catch ValueError as well, because ValueError is a subclass of Exception.
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
Example-1: Handle the ValueError for incorrect data · The script below should be placed in a Python file to collect the user's age value. The try block will throw the ValueError exception and output the custom error message if the user enters a non-numeric value for the age field.
🌐
Linux Hint
linuxhint.com › handling-value-error-exception-python
Handling the ValueError Exception in Python – Linux Hint
The output shows that the ValueError has occurred at line number 4 where the int() function has been used to covert the string, ‘Hello’. Create a Python file with the following script that will take the age value from the user. If a non-numeric value will be taken from the user for the age value, then the try block will throw the ValueError exception and print the custom error message.
🌐
LabEx
labex.io › tutorials › python-how-to-manage-valueerror-in-python-417443
How to manage ValueError in Python | LabEx
In this example, the code first attempts to convert the user's input to an integer, and then performs a division operation. If a ValueError is raised during the integer conversion, the first except block handles it.
🌐
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.
🌐
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 - This is a guide to Python ValueError. Here we discuss an introduction, how does it work, how to avoid valueError in python with examples.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Initial Commit
initialcommit.com › blog › valueerror-python
Python ValueError Exception – How to Identify & Handle
January 9, 2023 - The ValueError occurs when you input an incorrect value into a function, but the type of the value is correct. For example, if a function needs an int value, but you input a string instead, this would cause the TypeError, not ValueError.