Python数据文本文件等级程序 [英] Python data text file grades program
问题描述
def main():
inFile = open(grades.txt,r)
aList = inFile.readlines()
grades = [ F,E,D,C,B,A]
< h1>修改,以便程序运行
用于aList中的行:
n = lines.split()
print(n [0] [0] .lower()+ n [1] [0:4] .lower()+001+ grades [eval(n [2])])
inFile.close()
main()
如果有人能指出我犯了什么错误,那将不胜感激。解决方案
试着不给你明显的答案,在这里。信息范范辛中方亦亦读范范范范范范范范秘这就是:
用于aList中的行:
换句话说,for块中的所有内容,在这行之后,将执行列表中的每个元素...只要它在块中,
例如:
pre $ 2,3]:
print(a)
会显示1,2,3。 print(a)在for块中,因为它是正确缩进的。
然而:
$ b $ / pre>
在这里,print(x)不在块中。那么这里会发生什么? x将会得到1的值,然后是2,然后是3.然后才会打印x,并将其最后的值打印出来。
考虑到这一点,你应该能够发现你的代码有什么问题。
(顺便说一句,为了更安全,更pythonically的阅读你的文件,你应该看看这: https://docs.python.org/2 /tutorial/inputoutput.html#methods-of-file-objects ,尤其是段落末尾和with成语)。
Looking for help with my program. There is a text file with 5 first and last names and a number grade corresponding to each person. The task is to create a user name and change the number grade to a letter grade. The problem I am having is that the program is only outputting one line (or username) from the textfile and not all 5 lines (usernames).
def main():
inFile = open("grades.txt", "r")
aList = inFile.readlines()
grades = ["F","E","D","C","B","A"]
revised so that program will run
for lines in aList:
n = lines.split()
print(n[0][0].lower()+ n[1][0:4].lower()+ "001 "+ grades[eval(n[2])])
inFile.close()
main()
If anyone could point out where I am making the mistake it would be greatly appreciated.
OK... trying not to give you the obvious answer, here. Think about what you want to do : you want to do something "for each lines of aList". That is the meaning of :
for lines in aList:
In other words, everything in the "for" block, after this very line, will execute for each element inside aList... provided it is in the block, so properly indented.
For example :
for a in [1,2,3]:
print(a)
Will display 1,2,3. "print(a)" is in the for block, as it is properly indented.
However :
for a in [1,2,3]:
x = a
print(x)
Here, "print(x)" is NOT in the block. So what is going to happen here ? x will receive the value of 1, then 2, then 3. And only after that will x be printed, with the last value it received.
With that in mind, you should be able to spot what's wrong with your code.
(BTW, in order to read your file more safely and more "pythonically", you should have a look at this : https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects, particularly the end of the paragraph and the "with" idiom).
这篇关于Python数据文本文件等级程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!