Python 重复“尝试除块”直到满足条件
我写这段代码是为了把两个数字分开。我正在使用异常处理并正确捕获错误,但是,我想重复这个过程,直到除数不是用户给定的0(零)Python 重复“尝试除块”直到满足条件,python,Python,我写这段代码是为了把两个数字分开。我正在使用异常处理并正确捕获错误,但是,我想重复这个过程,直到除数不是用户给定的0(零) 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 Z
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')
现在,如果我将“b”设为0,它将显示“不能被零除”错误,这样就完成了。我希望能够重复Try and Exception块,直到用户没有为“b”给出0 这是
while
循环的一个好情况:
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')
你试过写一个循环吗?这能回答你的问题吗?