简体   繁体   中英

Returning a sum of squares function

So I need to write a program that takes three user inputs, a lower and upper bound, and the type of function to do (square, cube, inverse) So far, I have

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()

However, when I execute the program I get no errors, but just a blank output, no numbers or anything. What am I doing wrong?

A working, minimally modified version would look like this:

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()

Although you could remove a bit of the duplication in your code:

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

And if you want to compress it further, you can use list comprehension as well, just a code snippet here, eg:

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

or more generically using the function selector

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM