我有一个带有多个条件语句的函数。如果我有两个等于0的数字,则应打印“ Both Missing”。当我尝试减去数字时,它仍然尝试从0中减去0并进行除法,从而导致ZeroDivision错误:
line 51, in compare_sizes
whole_percent = subtract_f1_f2 / previous_size * 100
ZeroDivisionError: division by zero
我希望能够从两个值都为0的计算中忽略它,并且如果减法_f1_f2不转到条件语句。我的条件陈述的顺序错误吗?
from __future__ import division
def human_bytes(B):
"""Return the given bytes as a human friendly KB, MB or GB"""
B = float(B)
KB = float(1024) # 1024 B == 1KB
MB = float(KB ** 2) # 1,048,576 KB == 1MB
GB = float(KB ** 3) # 1,073,741,824 MB == 1GB
TB = float(KB ** 4) # 1,099,511,627,776 GB == 1TB
if B < KB:
return '{0} {1}'.format(B, 'Bytes' if 0 == B > 1 else 'Byte')
elif KB <= B < MB:
return '{0:.2f} KB'.format(B / KB)
elif MB <= B < GB:
return '{0:.2f} MB'.format(B / MB)
elif GB <= B < TB:
return '{0:.2f} GB'.format(B / GB)
def compare_sizes(previous_size, current_size):
subtract_f1_f2 = int(current_size - previous_size)
range_num = 0.4
range_previous_day = int(previous_size * range_num)
whole_percent = subtract_f1_f2 / previous_size * 100
if previous_size == 0 and not current_size == 0:
print("New File " + "\n")
if previous_size > 0 and current_size > 0 and previous_size == current_size:
print("Ok" + "\n")
if current_size == 0 and previous_size == 0:
print("Both Missing " + "\n")
if current_size == 0 and not previous_size == 0:
print ("Missing Current Number " + "\n")
if subtract_f1_f2 >= range_previous_day and subtract_f1_f2:
if subtract_f1_f2 == 0 :
pass
else:
print(human_bytes(previous_size) +" -> " + human_bytes(current_size) + " " +
"+" + str(whole_percent) + " % bigger" + "\n")
else:
print("Current Value Is In Range" + str(current_size) + "\n")
result = result = compare_sizes(1000,1000)
result = result = compare_sizes(0,0)
result = result = compare_sizes(0,1)
result = result = compare_sizes(0,1)
result = result = compare_sizes(1,0)
result = result = compare_sizes(1000,1400)
答案 0 :(得分:0)
您可以以最适合您的方式处理错误;
try:
whole_percent = subtract_f1_f2 / previous_size * 100
except ZeroDivisionError as e:
# for example
whole_percentage = 0
答案 1 :(得分:-2)
在输入任何if语句之前引发错误,您可以在正确的if语句中移动该行(即,其中previous_size!= 0为true的行)或使用类似以下内容的方法:
try:
whole_percent = subtract_f1_f2 / previous_size * 100
except:
whole_percent = "NA" ## or whatever value you want to return in this case