09-结合函数变量后,按操作符进行数字运算的改进

def my_sum(*number):  #加法操作
    sum1 = 0
    for item in number:
        sum1 += item
    return sum1
def my_mul(*number): #乘法操作
    sum1 = 1
    for item in number:
        sum1 *= item
    return sum1
def my_sum2(*number):  #减法操作
    sum1 = number[0]
    i =0               # i 用于判断遍历number时遍历到第几个元素
    for item in number:
        if i >0:
            sum1 -= item
        i += 1
    return sum1
def my_mul2(*number): #除法操作
    sum1 = number[0]
    i =0
    for item in number:
        if i >0 and item !=0:
            sum1 /= item
        elif item ==0:
            return "除数不能为0"
        i += 1
    return sum1
def get_method(method):
    if method == "+":
        return my_sum
    if method == "*":
        return my_mul
    if method == "/":
        return my_mul2
    if method == "-":
        return my_sum2

print(get_method("/")(1000,1,20,60,2))

运行效果:
print(get_method("/")(1000,1,20,60,2))
0.4166666666666667

print(get_method("/")(1000,1,0,60,2))
除数不能为0

print(get_method("-")(1000,1,0,60,2))
937

你可能感兴趣的:(09-结合函数变量后,按操作符进行数字运算的改进)