ele*_*357 0 python variable-assignment
我目前正在编写一个从txt文件中读取记录的程序,并在屏幕上打印数据:
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.
Run Code Online (Sandbox Code Playgroud)
这是它从中读取的文本文件:
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
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
# 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.")
Run Code Online (Sandbox Code Playgroud)
结果只是打印txt文件的最后一行并陷入循环.任何帮助将不胜感激.感谢您的时间.
为什么不在一个功能中完成所有操作 -
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
Run Code Online (Sandbox Code Playgroud)
所有这些功能都在这一个功能中压缩.你似乎编程很像C代码.这是Python!
globals
除非必须,否则尽量避免使用.只是我遵循的原则.显然在这种情况下你不需要.