'If not' 避免除零

'If not' to avoid zero division

我下面的代码 returns 当 occupied_spaces 为空时出现 zerodivision 错误。

occupied_spaces = [ ]

cars = occupied_spaces.count(1)
spaces = occupied_spaces.count(0)

if not occupied_spaces:
    print('The list is empty')
    
percentage = cars/len(occupied_spaces) * 100

print(percentage, '%')

有人可以解释为什么会这样吗?

你的问题不清楚,让我猜猜。看起来您想检查占用的空间是否为空,然后打印消息,否则计算百分比。所以代码应该是这样的。如果数组为空函数 len 将 return 你 0

occupied_spaces = [ ]

if not occupied_spaces:
    print('The list is empty')
else:
    percentage = occupied_spaces.count(1) / len(occupied_spaces) * 100
    print(percentage, '%')

看起来像 python 所以您需要正确对齐代码