如何实现重复Try Except块,直至用户输入的除数不为0?
Got it, the problem with your current code is that it only runs the input and calculation sequence once. If the user enters 0 as the divisor, it just shows the error message and terminates immediately. To make it repeat until a non-zero divisor is provided, we can wrap the input and try/except block in an infinite loop that exits only when the division succeeds.
Modified Code (Core Solution)
def in_num(): a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) return a, b # Loop indefinitely until valid division occurs while True: x, y = in_num() try: print(f'The Answer of {x}/{y} is {x/y}') break # Exit the loop once calculation is successful except ZeroDivisionError: print('Cant divide by zero. Please try again.')
How It Works:
- We use a
while Trueloop to create an infinite cycle of input and calculation attempts. - When the division runs without throwing a
ZeroDivisionError, we print the result and usebreakto exit the loop. - If the user enters 0 as the divisor, the exception is caught, we print an error message, and the loop restarts to prompt for new inputs.
Bonus: Handle Invalid Integer Inputs
Your current code will crash if the user enters non-integer values (like a string). To make it more robust, you can add an extra except block to catch ValueError:
def in_num(): a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) return a, b while True: try: x, y = in_num() print(f'The Answer of {x}/{y} is {x/y}') break except ZeroDivisionError: print('Cant divide by zero. Please try again.') except ValueError: print('Oops! Please enter valid whole numbers. Try again.')
This way, the program will handle both zero divisors and non-integer inputs gracefully, repeating until valid values are provided.
内容的提问来源于stack exchange,提问作者Mtoklitz113

