Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 重复“尝试除块”直到满足条件_Python - Fatal编程技术网

Python 重复“尝试除块”直到满足条件

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

我写这段代码是为了把两个数字分开。我正在使用异常处理并正确捕获错误,但是,我想重复这个过程,直到除数不是用户给定的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 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')

你试过写一个循环吗?这能回答你的问题吗?