首页 > 解决方案 > How to i add the return values of a loop

问题描述

I'm new to python a and I need to add the return values of a loop. the program is supposed to open a file containing dimensions in the format 1x31x6 sort them and do some math. I'm fairly certain I have everything right but I cannot figure out how to add the return values together. here is the code I have so far.

def parseAndSort(string):
    """this function reads the input file, parses the values, and sorts the ints from smallest to largest"""
    int_list = string.split('x')
    nums = [int(x) for x in int_list]
    nums.sort()
    length = nums[0]
    width = nums[1]
    height = nums[2]
    surface_area = (2 * length * width) + (2 * length * height) + (2 * width * height) + (length * width)
    tape = (2 * length) + (2 * width) + (length * width * height)
    return surface_area


def main():
    file = input('Please Input Measurement File :')
    try:
        output = open(file, "r")
    except FileNotFoundError:
        print("Error, please input a dimension file.")
    else:
        for ref in output:
            parseAndSort(ref)
        output.close()


if __name__ == "__main__":
    """ This is executed when run from the command line """
    main()

标签: python-3.xsumreturn-value

解决方案


我假设您的意思是您想要运行该函数的所有时间的返回值的总和。您可以保持一个运行总和,并不断将每个返回值添加到其中。

def main():
    sum = 0
    file = input('Please Input Measurement File :')
    try:
        output = open(file, "r")
    except FileNotFoundError:
        print("Error, please input a dimension file.")
    else:
        for ref in output:
            sum += parseAndSort(ref)
        output.close()
        print (sum)

推荐阅读