0

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.

jottbe
  • 4,228
  • 1
  • 15
  • 31
Job
  • 3
  • 1
  • You write, you have tried `try...except`. That should usually work. Can you please add your code? Basically, you should try to solve your homework yourself. Otherwise, you won't learn anything. If you post your code and the details about the problem you have with your solution, we can help you better. – jottbe Nov 30 '20 at 13:44

2 Answers2

0
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")
Abdalrhman Alkraien
  • 645
  • 1
  • 7
  • 22
  • that code will only handle division by zero error, other errors like if the user enter a string are not handled. – Job Dec 01 '20 at 18:57
0

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

DaSim
  • 363
  • 5
  • 10