我正在编写一个过程,从文本文件中提取信息,将文件从字符串转换为整数,对整数进行平方运算,最后将结果打印出来。代码的最后一部分(平方和)不起作用,我无法确定原因。我使用的是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
"""
你的代码有很多问题。不要在循环中定义函数。这不是一个好的编程实践,对你的程序影响很大。例如,在循环中使用result=[]时,每次result的值变为空,语句结果.append(a) 只有最新的价值。您还声明了result=[]两次。与其他变量相同。当您使用许多函数时,总是尝试传递和返回变量。像这样改变你的程序。你知道吗
您的代码中有一些错误。我的基本原则是让每一步都有自己的功能。您可以在一个函数中完成整个操作,但这会使以后很难添加内容。你知道吗
看看有单独的方法/函数有多有效?你知道吗
相关问题 更多 >
编程相关推荐