python3求和小工具:给定开始结尾数字及步长,以步长为间隔,
2020-09-03 本文已影响0人
AmanWang
说明
给定起始数,结尾数及步长,计算从起始数开始,以步长为间隔,到结尾数为止的所有数字的和,可以指定保留结果小数位数
startNum:起始数字
endNum:结尾数字
step:步长,必须为大于等于0的实数,否则默认为1
decimalLen:结果中保留的小数位数,只能设置0或正整数,否则默认使用startNum, endNum, step三者中最大的小数位数
源码
# 给定起始数,结尾数及步长,计算从起始数开始,以步长为间隔,到结尾数为止的所有数字的和,可以指定保留结果小数位数
def mySum(startNum, endNum, step, decimalLen=-1):
# 传参类型不对时直接返回false
if not isinstance(startNum, (int, float)) or not isinstance(endNum, (int, float)) or not isinstance(step, (
int, float)):
return False
# 保留小数位数decimalLen如果设置的不是0或者正整数,默认都使用startNum, endNum, step三个参数中最大的小数位数
if not isinstance(decimalLen, int) or decimalLen < 0:
decimalLen_startNum, decimalLen_endNum, decimalLen_step = 0, 0, 0
decimalLen_startNum_list = str(startNum).split('.')
decimalLen_endNum_list = str(endNum).split('.')
decimalLen_step_list = str(step).split('.')
if len(decimalLen_startNum_list) == 2:
decimalLen_startNum = len(decimalLen_startNum_list[1])
if len(decimalLen_endNum_list) == 2:
decimalLen_endNum = len(decimalLen_endNum_list[1])
if len(decimalLen_step_list) == 2:
decimalLen_step = len(decimalLen_step_list[1])
decimalLen = max([decimalLen_startNum, decimalLen_endNum, decimalLen_step])
# 步长为0或者开始的数字大于等于结尾的数字时,返回开始数和结尾数的和
if step == 0 or startNum >= endNum:
sum = startNum + endNum
if decimalLen == 0:
sum = int(sum)
else:
sum = round(sum, decimalLen)
return sum
# 步长不能小于0,否则设置为默认值1
if step < 0:
step = 1
sum = 0
while True:
sum = sum + startNum
startNum = startNum + step
if startNum >= endNum:
startNum = endNum
sum = sum + startNum
break
if decimalLen == 0:
sum = int(sum)
else:
sum = round(sum, decimalLen)
return sum
测试结果
# 引用
if __name__ == '__main__':
print('结果1:',mySum(1, 10, 2))
print('结果2:',mySum(-10, 10, 4, 3))
print('结果3:',mySum(-10, 10, -1))
print('结果4:',mySum(-101, 10, -1))
print('结果5:',mySum(1, 10, 1.443))
print('结果6:',mySum(1, 10, 1.443, 2))
print('结果7:',mySum(1, 10, 0, 0))
print('结果8:',mySum(4.342, 10.41221, 0))
print('结果9:',mySum(4.342, 10.41221, 0, 2))
print('结果10:',mySum(4.342, 10.41221, 0, 0))
# 结果
结果1: 35
结果2: 0
结果3: 0
结果4: -5096
结果5: 47.303
结果6: 47.3
结果7: 11
结果8: 14.75421
结果9: 14.75
结果10: 14