1

So, I have this code, works very fine, but I want to have possibility if I input x it will return me to the beginning of choosing list I have

def ask2():
while True:
    try:
        number = int(input('Pick a number in range 1-100: '))
    except ValueError:  # just catch the exceptions you know!
        print('That\'s not a number!')
    else:
        if 1 <= number <= 100:  # this is faster
            print("added")
        else:
            print('Out of range. Try again')
4
  • 1
    finally ? docs.python.org/2.5/whatsnew/pep-341.html Commented Mar 3, 2020 at 13:43
  • Then when I add finally it says local variable number might be referenced before assignment Commented Mar 3, 2020 at 13:50
  • initialize the variable before Commented Mar 3, 2020 at 13:51
  • I would just put "continue" where you print "added" to break out of the while True. However, since it's inside a function, you can use "return" instead. Commented Mar 3, 2020 at 14:14

1 Answer 1

1

Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean:

try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block

The code in block-1 is executed. If the code raises an exception, the various except blocks are tested: if the exception is of class Exception1, handler-1 is executed; otherwise if it's of class Exception2, handler-2 is executed, and so forth. If no exception is raised, the else-block is executed.

No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.


PEP 341: Unifying try-except and try-finally

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.