Python 错误 : [ZeroDivisionError: division by zero]

标签 python python-3.x

我有一个关于我的 python 代码的问题。我还在学习,所以请不要介意任何错误。作业是计算某人在正常年份和金星年份的年龄。

平年很容易,但金星年有点难。

a = input("What is your name? ")
b = input("What is your birth year? ")
c = 2019
d = 0.62

# calculating age
try:
    e = int(c) - int(b)
except ZeroDivisionError:
    e = 0

# calculating age in venus years
try:
    f = int(e) / int(d)
except ZeroDivisionError:
  f = 1


print('Dear',a,','' in 2019 your age will be ',e,'.',sep='')
print('And your age is',f,'in Venusyears.')

我遇到的问题是总是将 f 视为 0。但如果我不这样做:

    f = int(e) / int(d)
except ZeroDivisionError:
  f = 1

它会给我一个 ZeroDivisionError,因为 e 还不是一个数字(还)。

有人可以向我解释如何解决这个问题吗?

希望收到您的来信!

亲切的问候,

最佳答案

ZeroDivisionError 不是由 e 不是数字引起的。这是由于试图将一个数除以 int(d) 引起的,因为 int(d) 为零。

d 是一个值为 0.62 的 float 。如果将其转换为整数,则会得到零。

你可以除以 float 本身:

f = int(e) / d

这会给你另一个 float 。如果你想要它作为一个整数,你可以将它转换为一个:

f = int(int(e) / d)

这不会导致 ZeroDivisionError,因为 d 在您的代码中明确为非零值。

关于Python 错误 : [ZeroDivisionError: division by zero],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58027537/

相关文章:

python - 按多列 pandas 中的值计数进行透视

python - 这是创建 numpy 数组的只读 View 的正确方法吗?

python - python 中的 float 给出了错误的答案

python-3.x - 对本地主机的多个异步请求的 Aiohttp 错误 "Connect call failed"

python - time.sleep 使图片循环不显示

python - Python 3 中按对象迭代

python - Seaborn 多轴图将不同颜色分配给相同/共享类别色调

python - Numpy 逻辑和

python - 使用 pandas 和 dask 合并具有不同模式的 Parquet 文件

python - 将我的 Google Geocoding API key 与 Python 地理编码器一起使用