'If not' 以避免零除法

zerodivision我下面的代码在为空时返回错误occupied_spaces。


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, '%')

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


慕尼黑5688855
浏览 96回答 1
1回答

皈依舞

你的问题不清楚,但让我猜猜。看起来您想检查占用的空间是否为空,然后打印消息,否则计算百分比。所以代码应该是这样的。如果数组为空函数 len 将返回 0occupied_spaces = [ ]if not occupied_spaces:    print('The list is empty')else:    percentage = occupied_spaces.count(1) / len(occupied_spaces) * 100    print(percentage, '%')看起来像它的 python 所以你需要正确对齐代码
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python