Python 多个功能,但有一个功能失败
我正在编写一个过程,从文本文件中提取信息,将文件从字符串转换为整数,对整数进行平方运算,并在最终打印结果之前对平方进行求和。代码的最后一部分(平方和)不起作用,我无法确定原因。我正在使用Python 3.7.2。任何帮助都将不胜感激Python 多个功能,但有一个功能失败,python,function,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 num
"""
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
"""
你的代码有很多问题。不要在循环中定义函数。这不是一个好的编程实践,对您的程序影响很大。例如,当在循环中使用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)
您的代码中有一些错误。我的基本原则是让每一步都有自己的功能。您可以在一个函数中完成整个操作,但这使得以后很难添加内容
# 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
“不工作”是一个非常不精确的错误描述。错误或输出是什么,预期的输出和行为是什么(编辑问题以将其显示为正确格式的文本)?听起来好像您知道其中一个不起作用。您是如何确定的?我想您可能会发现,如果不在循环中定义函数,代码可能会正常工作。你真的不应该在循环中定义函数。它有很多陷阱,我能想到的唯一好处(我不知道)是,如果你用可变参数做事情,我会说,如果你想做的话,只在循环中定义一个函数。当然有一些有效的用例……我很感谢您的反馈。我不喜欢在循环中使用函数,因为我认为它没有那么容易遵循。我真的很喜欢您定义所有内容的方式,以及代码的易操作性。这帮了大忙。谢谢。我真的很喜欢你定义一切的方式,而且代码更容易理解。老实说,我从这个建议中学到了很多。