多种功能,但其中一项失败

时间:2019-04-10 23:49:59

标签: python function

我正在编码一个过程,以从文本文件中提取信息,将文件从字符串转换为整数,对整数进行平方,并对平方求和,然后最终打印结果。代码的最后部分(对平方求和)不起作用,我无法确定原因。我正在使用Python 3.7.2。任何帮助将不胜感激。

"""
Use the functions from the previous three problems to implement a main() program that computes the sums of the squares of the numbers read from a file.
Your program should prompt for a file name and print out the sum of the squares of the numbers in the file.
Hint: You may want to use readline()

Test Cases
Input(s)  :  Output(s)
4numsin.txt  

"""
def main():
    f = open("4numsin.txt", "r")
    for line in f:
        line = line.strip()
        strNumber = line
        number = []
        result = []

        def toNumbers():
            for n in strNumber:
                n = int(strNumber)
                x = number.append(n)
            return number
        toNumbers()

        for line in number:
            def squareEach():
                z = 0
                result = []
                while number != []:
                    z = number.pop(0)
                    a = int(z) ** 2
                    b = result.append(a)
                print(strNumber, result)
            squareEach()

        while result != []:
            def Total():
                i = 0
                theSum = 0
                i = result.pop()
                theSum += i
            print(theSum)
            Total()
main()

"""Text File:
4numsin.txt
0
1
2
3
4
5
6
7
8
"""

2 个答案:

答案 0 :(得分:0)

您的代码中有很多问题。切勿在循环内定义函数。这不是一个好的编程习惯,并且会严重影响您的程序。例如,当您在循环中使用result = []时,每次将result的值设置为空,并且语句result.append(a)中仅包含最新的值。另外,您已经两次声明了result = []。与其他变量相同。使用许多函数时,请始终尝试传递和返回变量。像这样更改程序。

def readfile(filepath):
    #Your code to read the contents and store them
    return number_list

def squares(n):
    #code to square the numbers, store and return the numbers
    return ans

def Total():
    #code to calculate the sum
    # you can also check out the built-in sum() function
    return sum

def main():
    numbers = readfile(filepath)
    sq = squares(numbers)
    result = Total(sq)

答案 1 :(得分:0)

您的代码中有些错误。我的基本原则是使每个步骤都具有自己的功能。您可以在一个函数中完成全部操作,但是以后很难添加。

# Opens the file and appends each number to a list, returns list
def open_file(filename):
    output = []
    f = open(filename, "r")
    for line in f:
        output.append(int(line.strip()))
    return output

# Takes an input like a list and squared each number, returns the list
def square_number(input):
    return [num*num for num in input]

# sums the list
def sum_numbers(input):
    return sum(input)

# the start, function calls within function calls
the_sum = sum_numbers(square_number(open_file('4numsin.txt')))

#check the result
print(the_sum)
>> 204

看看拥有独立的方法/功能有多有效?

# look at other things
print(open_file('4numsin.txt'))
>> [0, 1, 2, 3, 4, 5, 6, 7, 8]

print(sum_numbers(open_file('4numsin.txt')))
>> 36