pythonexceptionerror-handlinginvalid-characters

python handling invalid inputs from a user


I am stuck with this homework:

rewrite the following program so that it can handle any invalid inputs from user.

def example():
   for i in range(3)
       x=eval(input('Enter a number: '))
       y=eval(input('enter another one: '))
       print(x/y)

l tried tried the try... except ValueError, but the program is still failing to run.


Solution

  • That's because you probably didn't consider the ZeroDivisionError that you get when y = 0! What about

    def example():
       for i in range(3):
          correct_inputs = False
          while not correct_inputs:
             try:
                x=eval(input('Enter a number: '))
                y=eval(input('enter another one: '))
                print(x/y)
                correct_inputs = True
             except:
                print("bad input received")
                continue
    

    This function computes exactly 3 correct divisions x/y! If you need a good reference on continue operator, please have a look here