Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ';如果不是';避免零除法_Python_Divide By Zero - Fatal编程技术网

Python ';如果不是';避免零除法

Python ';如果不是';避免零除法,python,divide-by-zero,Python,Divide By Zero,当已占用的\u空格为空时,下面的代码返回一个零除法错误 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, '%') 有人

已占用的\u空格
为空时,下面的代码返回一个
零除法
错误

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

有人能解释一下为什么会这样吗?

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

我假设len是为了得到数组的大小,所以若占用的空间为空,则大小为0。看起来像是python,所以若数组为空,它将只打印列表为空的消息,然后转到pecentage CalculationWhat you mean what this become?如果
已占用的\u空格
为空,则其
len
0
。所以你不能做
汽车/len(占用的空间)
。。。您可能希望将最后两行放在
else