mailrenegade
mailrenegade

Reputation: 15

How to stop try/except looping back to first input?

So I have the following code to catch user input errors:

while True:
     try:
        number1 = int(input('Number1: '))
        assert  0 < number1 < 10
        number2 = int(input('Number2: '))
        assert  0 < number2 < 10
        number3 = int(input('Number3: '))
        assert  0 < number3 < 10
        number4 = int(input('Number4: '))
        assert  0 < number4 < 10
    except (ValueError, AssertionError):
        print("Not valid")
    else:
        break

My problem is that if my user makes a mistake on entering number4 then the loop resets and they have to enter the first 3 numbers again. I would like instead to find a way to return to the number that they just entered incorrectly (preferably without using a while loop for each individual input).

Thanks in advance!

Upvotes: 0

Views: 42

Answers (2)

bug
bug

Reputation: 4130

Just extract the piece asking for a number:

def input_number(message):
  while True:
    try:
      number = int(input(message))
      assert  0 < number < 10
    except (ValueError, AssertionError):
      print("Not valid")
    else:
      return number

number1 = input_number('Number1: ')
number2 = input_number('Number2: ')
number3 = input_number('Number3: ')
number4 = input_number('Number4: ')

A side note about assert: is best practice avoid to use of assert for cases like this because if you run python in optimized mode then they are stripped away, truth is that the optimized mode is usually not used.

Upvotes: 3

Prune
Prune

Reputation: 77837

If you want individual handling for each input, then you need to write your code that way. You wrote this as an all-or-nothing block. The obvious way is to have individual blocks for each input. The more usable way is to loop through your inputs and re-use a single try-except.

num_list = []
for i in range(4):
    while True:
        try:
            num = int(input('Number ' + str(i) + ' : '))
            assert  0 < number1 < 10
        except (ValueError, AssertionError):
            print("Not valid")

        num_list.append(num)

Also see loop until valid response

Upvotes: 1

Related Questions