python handling invalid inputs from a user

769 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

1
On
def example():

   for i in range(3)
      try:
         x=eval(input('Enter a number: '))
      except ValueError:
         print("Sorry, value error")
      try:
         y=eval(input('enter another one: '))
      except ValueError:
         print("Sorry, value error")`enter code here`
      try:
         print(x/y)
      except ValueError:
         print("Sorry, cant divide zero")