gpt4 book ai didi

python - 编写一个程序计算文件中存储的所有数字的平均值

转载 作者:行者123 更新时间:2023-12-01 06:40:35 26 4
gpt4 key购买 nike

'''
Average Number
'''

def main ():
import sys
try:
NumberTxt = open("numbers.txt", "r")
except IOError as e:
print ("Non-numeric data found in the file /n press enter" )
except (ValueError):
print( "Non-numberic data found in the file /n press enter")
else:
TotalNumber = 0
NumbersOfLines = 0
line = NumberTxt.readline()

while line !="":
NumbersOfLines += 1
TotalNumber += int( line )
line = NumberTxt.readline()
averageNumbers = TotalNumber / NumbersOfLines

print ( "The average is:", averageNumbers)
print ( "press enter" )

main()

最佳答案

如果信息不完整,最有可能的原因是因为你从文件中读取的行末尾仍然有换行符,所以最后一行只是换行符\n,所以while 仍然为 true,但是 int("\n") 失败。因此,要修复更改这两行:

line = NumberTxt.readline().strip() # Strip leading and trailing spaces and newlines

while line: # Not strictly necessary, but more Pythonic to test this way

关于python - 编写一个程序计算文件中存储的所有数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com