为了账号安全,请及时绑定邮箱和手机立即绑定

'If not' 以避免零除法

'If not' 以避免零除法

慕尼黑5688855 2023-02-12 19:01:07
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) * 100print(percentage, '%')有人可以解释为什么会这样吗?
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

你的问题不清楚,但让我猜猜。看起来您想检查占用的空间是否为空,然后打印消息,否则计算百分比。所以代码应该是这样的。如果数组为空函数 len 将返回 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 所以你需要正确对齐代码


查看完整回答
反对 回复 2023-02-12
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信