Home > Enterprise >  How can I make this loop keep going until the correct input is entered?
How can I make this loop keep going until the correct input is entered?

Time:07-02

This is the code that I have written, I am learning python right now but tell me how can I make this loop keep on going until we hit the correct condition that is x and y are both integers and y > 0, so that it won't be able to throw an exception.

def problem_2():
    while True:
        try:
            x = int(input("Enter the value of X"))
            y = int(input("Enter the value of Y"))
            print(x/y)
        except ZeroDivisionError:
            print("You have divided the number by zero")
        except TypeError:
            print("Please Enter Integer in both the cases")

problem_2()

CodePudding user response:

You can simply make a infinite while loop take x and y as input and check you condition.

  1. If your condition are met then do the processing which you want to do and break the loop.
  2. If you condition are not met then just continue the loop again and same thing will repeat until you conditions are met.
while true:
    #take your input
    #check your condition 
    #if condition not met 
        continue
    #if condition met
        #do your stuff
        break

CodePudding user response:

Check if y > 0 after your exception catching blocks:

def problem_2():
    while True:
        try:
            x = int(input("Enter the value of X"))
            y = int(input("Enter the value of Y"))
            print(x/y)
        except ZeroDivisionError:
            print("You have divided the number by zero")
        except TypeError:
            print("Please Enter Integer in both the cases")
        # No exception was raised, check y
        if y > 0:
            break

problem_2()

Alternatively, to avoid using exception handling altogether, you can do it like this:

def problem_2():
    while True:
        x = input("Enter the value of X")
        y = input("Enter the value of Y")
        if not x.isdigit() or not y.isdigit():
            print("Please enter Integer in both the cases")
            continue
        x, y = int(x), int(y)
        if x == 0 or y == 0:
            print("Cannot divide by zero")
            continue
        # If we reached here, the input is valid
        print(x/y)
        break

problem_2()

CodePudding user response:

Try this one i hope it will work perfect for what you are wanting.Thanks

def problem_2():
    while True:
        x = input("Enter the value of x: ")
        y = input("Enter the value of y: ")
        if x.isdigit() and y.isdigit():
            if int(y)>0:
                print(int(x)/int(y))
            else:
                pass 
        else:
            continue
problem_2()
  • Related