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 OverflowPython: if error raised I want to stay in script - Stack Overflow
Python: else ValueError: (Specifically ValueError In This Case) - Stack Overflow
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
except VS except valueError: what's the difference?
Videos
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..."
...
success = false
while not success:
try:
value = raw_input('please enter an integer')
int(value)
success = true
except:
pass
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!")
try and except are a form of control flow. Essentially, it means try to run this code, except if an exception occurs (such as ValueError) do something else.
if and else are another form of control flow. Together, they mean if a condition is true, do something; else, do something else.
An exception occurring is not a condition, and thus it would not make sense to use else with an exception like ValueError. Instead, you want to use the try/except block.
Hi there,
I've been learning Python for some months now (still a beginner though!) and so far I encountered no issues when using a simple except in errors handling. But I came across except valueError many times in other people's codes, and I was wondering what was the difference between these two.
All I could find on the Internet was the use of the except valueError when raising an error, but I don't think I understood how it's different from except alone. Also it seems like this latter is barely mentioned anywhere I looked...
Any help appreciated!
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.