Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我是不是缺少打印命令了?_Python_File_For Loop - Fatal编程技术网

Python 我是不是缺少打印命令了?

Python 我是不是缺少打印命令了?,python,file,for-loop,Python,File,For Loop,我的任务是制作一个程序,从文件中读取数字,然后显示这些数字的平均值。因此: def main (): #open the file numbers.txt, this file is located in the IDLE directory #on my flash drive. numbers_file = open(r'{file path}\numbers.txt', 'r') number_total = 0 #read each line of

我的任务是制作一个程序,从文件中读取数字,然后显示这些数字的平均值。因此:

def main ():
    #open the file numbers.txt, this file is located in the IDLE directory
    #on my flash drive.
    numbers_file = open(r'{file path}\numbers.txt', 'r')
    number_total = 0
    #read each line of the file, numbers.txt
    line = numbers_file.readline()
    #declare a line counter, this will be needed to determine the average of
    #all the numbers in the file
    line_number = 1
    #check that the line is valid, as long as an emptry string is not
    #returned, continue
    while line != '':
        #convert the line to a float
        number_entry = float(line)
        #count what line that was
        line_number += 1
        #add the current number in the line to the total of the lines so far
        number_total += number_entry
    #when the last line is read,
    file_average = number_total/line+number
    numbers_file.close()
    print(file_average)

#call the main function
main ()
我运行它。。。我等着。。。等啊等啊等啊


numbers.txt
中只有10个数字;这应该在一瞬间完成。我错过了什么?

行在循环中没有变化,也没有中断;一旦你进入循环,你就被卡住了。我希望您需要的是在循环中移动(或复制)读线

while line != '':
    number_entry = float(line)
    line_number += 1
    number_total += number_entry

    #read the next line
    line = numbers_file.readline()

你在读第一行时只带着

line = numbers_file.readline()
然后在
while
循环中,您希望
行的值发生变化。这将要求您也在循环中调用
readline
方法。但您有一个更具python风格的选项,利用
文件
对象实现
迭代器
接口这一事实

删除
line=numbers\u file.readline()
并在line!=''时更改
循环到:

for line in numbers_file:

在while循环之后,使用
line
设置平均值。真的需要吗。或者,您是否找到每一行的平均值,然后放入while循环。

您的while循环在任何地方都没有中断。目前,您没有遍历该文件。你读了第一行,然后进入一个无限循环,它永远不会读下一行!是的,就是这样。总是简单的东西。虽然现在我有了一个新的。。。并发症。程序运行,添加数字,然后显示平均值,但它不是正确的平均值。目前,numbers.txt包含数字1-10(1,2,3…),将这些数字加起来等于55,除以10,应该等于5.5。但程序显示为5.0。我将file_average声明为float,但没有任何效果。见鬼,文件的平均值是一个浮点数,我在第一次运行程序并得到结果时就改变了它。啊,对了,问题出在
line\u number=1
上。将其更改为
line\u number=0
。无需担心。我的错误。我忘了我改了一些东西来解决问题。谢谢。我的意思是循环之前的赋值,而不是循环内部的递增。这是一种类型。它不是“数字总数/行+数”,而是“数字总数/行总数”。
 file_average = number_total/line+number