Python: if the error is raised, I want to stay in the script

I am making some practice problems from online using python, and I have a question about how to stay in a script if an error occurs. For example, I want to read values ​​from a prompt and compare them with the value of an integer value inside a script. The only problem is that when someone enters something other than the number 'int (value)' (ex. Value = 'fs'), an error occurs and exits the script. I want this to happen, if that happens, I stay inside the script and ask for a different value at the prompt.

+3
source share
6 answers

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..."
...
+4
source

try... except, python

+1
source

Read here try: except:idiom here

+1
source

How to catch him?

try:
    a = int('aaa')
except ValueError:
    print('Still working')
0
source
success = false
while not success:
    try:
        value = raw_input('please enter an integer')
        int(value)
        success = true
    except:
        pass
0
source

All Articles