陷入了while循环,请帮忙!
我现在正在写一个程序,这个程序可以从一个文本文件中读取记录,然后把数据打印到屏幕上,像这样:
GRADE REPORT
NAME COURSE GRADE
-----------------------------------------------------------
JOE FRITZ AMERICAN GOVERNMENT B
CALCULUS I A
COMPUTER PROGRAMMING B
ENGLISH COMPOSITION A
Total courses taken = 4
LANE SMITH FUND. OF DATA PROCESSING B
INTERMEDIATE SWIMMING A
INTRO. TO BUSINESS C
Total courses taken = 3
JOHN SPITZ CHOIR C
COLLEGE STATISTICS B
ENGLISH LITERATURE D
INTRO. TO BUSINESS B
Total courses taken = 4
Total courses taken by all students = 11
Run complete. Press the Enter key to exit.
这是它读取的文本文件:
JOE FRITZ AMERICAN GOVERNMENT B
JOE FRITZ CALCULUS I A
JOE FRITZ COMPUTER PROGRAMMING B
JOE FRITZ ENGLISH COMPOSITION A
LANE SMITH FUND. OF DATA PROCESSING B
LANE SMITH INTERMEDIATE SWIMMING A
LANE SMITH INTRO. TO BUSINESS C
JOHN SPITZ CHOIR C
JOHN SPITZ COLLEGE STATISTICS B
JOHN SPITZ ENGLISH LITERATURE D
JOHN SPITZ INTRO. TO BUSINESS B
这是我的代码:
# VARIABLE DEFINITIONS
name = ""
course = ""
grade = ""
recordCount = 0
eof = False
gradeFile = ""
#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS
#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS
def startUp():
global gradeFile
gradeFile = open("grades.txt","r")
print ("grade report\n").center(60).upper()
print "name".upper(),"course".rjust(22).upper(),"grade".rjust(32).upper()
print "-" * 60
readRecord()
def readRecord():
global name, course, grade
studentRecord = gradeFile.readline()
if studentRecord == "":
eof = True
else:
name = studentRecord[0:20]
course = studentRecord[20:50]
grade = studentRecord[50:51]
eof = False
def processRecords():
numOfRecs = 0
while not eof:
numOfRecs += 1
printLine()
readRecord()
return numOfRecs
def printLine():
print name, course.rjust(3), grade.rjust(3)
def closeUp():
gradeFile.close()
print "\nTotal courses taken by all students = ",recordCount
#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC
startUp()
recordCount = processRecords()
closeUp()
raw_input("\nRun complete. Press the Enter key to exit.")
但是结果只打印了文本文件的最后一行,而且程序一直在循环中。任何帮助都非常感谢。谢谢你的时间。
7 个回答
3
在这个设计中,"eof"需要被添加到readRecord()函数的全局变量列表里。
否则,如果只是简单地给它赋值,就会创建一个新的局部变量,而processRecords()函数是看不到这个局部变量的。
4
你需要在 readRecord()
函数里把 eof
声明为 global
:
def readRecord():
global eof, name, course, grade
否则,当 studentRecord
为空时,你对 eof
所做的修改就无法在 readRecord()
函数外部使用了。
5
你为什么不把所有的东西都放在一个函数里呢?
def processRecords():
print ("grade report\n").center(60).upper()
print "name".upper(),"course".rjust(22).upper(),"grade".rjust(32).upper()
print "-" * 60
rec_count = 0
for line in open("grades.txt","r"):
name = line[0:20]
course = line[20:50]
grade = line[50:51]
print name, course.rjust(3), grade.rjust(3)
rec_count += 1
return rec_count
把所有这些功能都压缩到一个函数里。你看起来编程的方式很像C语言的风格。这里是Python啊!
另外,尽量避免使用globals
,除非真的需要。我个人遵循这个原则。在这种情况下,显然你并不需要这样做。