1 def main(): 2 fileName=input("What file are the numbers in?") 3 infile=open(fileName,‘r‘) 4 sum=0 5 count=0 6 for line in infile: 7 sum=sum+eval(line) 8 count=count+1 9 print("\nThe average of the numbers is",sum/count) 10 main()
方法二:
采用readline()方法的end-of-file循环模式
1 line=infile.readline() 2 while line!="" 3 #处理每一行 4 line=infile.readline()
==========================
循环嵌套
*决策和循环相互嵌套可以实现复杂算法
*如果数字以逗号分隔出现在文件的同一行上
1 for xStr in line.split(",") 2 sum=sum+eval(xStr) 3 count=count+1
原文:http://www.cnblogs.com/simon930/p/6486408.html