多个功能,但有一个功能失败

2024-09-29 21:36:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个过程,从文本文件中提取信息,将文件从字符串转换为整数,对整数进行平方运算,最后将结果打印出来。代码的最后一部分(平方和)不起作用,我无法确定原因。我使用的是python3.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
"""

Tags: oftheintxtnumberformaindef
2条回答

你的代码有很多问题。不要在循环中定义函数。这不是一个好的编程实践,对你的程序影响很大。例如,在循环中使用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)

您的代码中有一些错误。我的基本原则是让每一步都有自己的功能。您可以在一个函数中完成整个操作,但这会使以后很难添加内容。你知道吗

# 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

相关问题 更多 >

    热门问题