如果您只想要一个代表无穷大的浮点数,您可以发出float('inf')或float('-inf')。
标准Python浮点数和整数会给你一个ZeroDivisionError,但你可以使用numpy数据类型。
>>> import numpy as np
>>> np.float64(15)/0
inf
Run Code Online (Sandbox Code Playgroud)
没有numpy,写一个函数:
def my_div(dividend, divisor):
try:
return dividend/divisor
except ZeroDivisionError:
if dividend == 0:
raise ValueError('0/0 is undefined')
# instead of raising an error, an alternative
# is to return float('nan') as the result of 0/0
if dividend > 0:
return float('inf')
else:
return float('-inf')
Run Code Online (Sandbox Code Playgroud)