1

I made a function that validates 2 variables provided by user in input. I have two problems:

  1. In the function break giving me and error: break outside loop. I can not fix it.
  2. If input is sent to function and when it fails, how can I send it back to input for user to re-enter?

Please find below code:

def testify(arg_test):
    while True:
        i =  arg_test
    try:
        i == int(i)
    except ValueError as e:
      print ("Enter valid int value")
    else:   
         break
    return arg_test

number_1 = input("Write first number: ");
number_2 = input("Write second number: ");

arg_number_1 = testify(number_1);
arg_number_2 = testify(number_2);
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

You have indentation issues in your code, please take a look to this fix:

def testify(arg_test):
    i =  arg_test
    try:
        int(i) # This is sufficient to test if arg_test could be parsed as an integer
        return arg_test
    except ValueError as e:
        new_input = input("Enter valid int value")
        return testify(new_input)

Edit: Changed my answer to use a recursive function that checks new inputs from the user.

EnriqueBet
  • 1,482
  • 2
  • 15
  • 23
  • in except statement you can make it a reccursive function to solve back problem 2 – Pradeep Padmanaban C May 05 '20 at 20:52
  • With this change it uses a recursive function, if the input is valid, then it returns the original argument, otherwise, it will enter again into the function and therefore the loop is not needed. – EnriqueBet May 05 '20 at 20:56
1

First, the question I'm most sure about: 2) re-enter variable after your try except error.

I would just do the following code:

else:
    break()
    testify(arg_test)

The 1st question I am not so sure about, the break function as it is rarely used by me! But I would say: try indenting your try and except loop so it is underneath the while True: loop!

Like this:

def testify(arg_test):
    while True:
        i =  arg_test
        try:
            i == int(i)
        except ValueError as e:
            print ("Enter valid int value")
        else:   
            break
            testify(arg_test)
    return arg_test

Hope this helps!