-2

I've written this code to divide two numbers. I am using exception handling and catching the error right but, I want to repeat the process, till the divisor is not given as 0 (zero) by the user.

def in_num():
    a=int(input('Enter a number: '))
    b=int(input('Enter another number: '))
    return a,b

x, y=in_num()

try:
    print(f'The Answer of {x}/{y} is {x/y}')
    
except ZeroDivisionError:
    print('Cant divide by zero')
    

Now, if I give the 'b' as 0, it'll display the 'Cant divide by zero' error and it's done. I want to be able to repeat the Try and Except block till the user doesn't give 0 for 'b'!

Mtoklitz113
  • 3,828
  • 3
  • 21
  • 40
  • 1
    Did you try writing a loop? – mkrieger1 Sep 19 '20 at 12:57
  • 2
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Wups Sep 19 '20 at 12:58

1 Answers1

1

This is a good situation for a while loop:

def in_num():
    a = int(input('Enter a number: '))
    b = int(input('Enter another number: '))
    return a, b

while True:
    x, y = in_num()
    try:
        print(f'The Answer of {x}/{y} is {x/y}')
        break # this stops the loop
    except ZeroDivisionError:
        print('Cant divide by zero')
Jasmijn
  • 9,370
  • 2
  • 29
  • 43