You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现重复Try Except块,直至用户输入的除数不为0?

Solution for Repeating Division Until Valid Divisor is Entered

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 True loop to create an infinite cycle of input and calculation attempts.
  • When the division runs without throwing a ZeroDivisionError, we print the result and use break to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:22:45