返回平方和函数

时间:2018-02-20 19:53:55

标签: python sum return

所以我需要编写一个程序,它接受三个用户输入,一个下限和上限,以及要做的函数类型(square,cube,inverse) 到目前为止,我有

def main():
    global func
    lower = int(input("Enter the lower bound for summation: "))
    upper = int(input("Enter the upper bound for summation: "))
    func = str(input("Enter a function to be summed (Square, cube, inverse)"))
    summation(lower,upper)
def summation(low,high):
    tot = 0
    if func.lower() == 'square' and low < high:
        for i in range(low, high + 1):
            sqr = i**2
            tot += sqr
    return tot
    if func.lower() == 'cube' and low < high:
        for i in range(low, high + 1):
            cub = i**3
            tot += cub
    return tot
    if func.lower() == 'inverse' and low < high:
        for i in range(low, high + 1):
            inv = (1/i)
            tot += inv
    return tot

if __name__ == '__main__':
    main()

但是,当我执行程序时,我没有错误,只是一个空白输出,没有数字或任何东西。我做错了什么?

1 个答案:

答案 0 :(得分:0)

一个工作的,最低限度修改的版本看起来像这样:

def main():
    global func
    lower = int(input("Enter the lower bound for summation: "))
    upper = int(input("Enter the upper bound for summation: "))
    func = str(input("Enter a function to be summed (Square, cube, inverse)"))
    print(summation(lower,upper))

def summation(low,high):
    tot = 0
    if func.lower() == 'square' and low < high:
        for i in range(low, high + 1):
            sqr = i**2
            tot += sqr
        return tot

    if func.lower() == 'cube' and low < high:
        for i in range(low, high + 1):
            cub = i**3
            tot += cub
        return tot
    if func.lower() == 'inverse' and low < high:
        for i in range(low, high + 1):
            inv = (1/i)
            tot += inv
        return tot

if __name__ == '__main__':
    main()

虽然您可以删除代码中的一些重复内容:

def summation(low, high, func):
    tot = 0
    fn_select = {'square': lambda x: x**2, 'cube': lambda x: x**3, 'inverse': lambda x: 1/x}
    if low < high:
        for i in ranage(low, high+1):
            tot += fn_select[func](i)
        return(tot)
    else:
        raise ValueError('Lower bound needs to be lower than higher bound')

如果你想进一步压缩它,你也可以使用列表理解,这里只是一个代码片段,例如:

tot = sum( [ x**2 for x in range (low, high+1) ])

或更通常使用函数选择器

tot = sum( [fn_select[func](x) for x in range(low, high+1) ])