【发布时间】:2012-10-25 17:01:31
【问题描述】:
我不知道如何解决这个问题。我试过重新输入程序。
最后一个主函数出现意外的缩进错误。
resident = 81
nonresident = 162
def main():
# initialize counters and total tuition
resident_counter = 0
nonresident_counter = 0
total_tuition = 0
print("Name \tCode\tCredits\tTuition")
print
try:
# open the data file
infile = open('enroll.txt', 'r')
# read the first value from the file
student_name = infile.readline()
# continue reading from file until the end
while student_name != '':
# strip the new line character and print the student's name
student_name = student_name.rstrip('\n')
print(student_name, end='\t')
# read the code type, strip the new line, and print it
code = infile.readline()
code = code_type.rstrip('\n')
print(code_type, end='\t')
# read the number of credits, strip the new line, and print it
credits = infile.readline()
credits = int(credits)
print(format(credits, '3.0f'), end='\t')
# check the room type and compute the rental amount due
# increment the appropriate counter
if code_type == "R" or room_type == "r":
payment_due = credits * resident
resident_counter += 1
elif code_type == "N" or room_type == "n":
payment_due = credits * nonresident
nonresident_counter += 1
elif code_type != "R" or code_type != "r" or code_type != "N" or code_type != "n":
payment_due = 0
# accumulate the total room rent
tuition += payment_due
# print the appropriate detail line
if payment_due == 0:
print('invalid code')
else:
print('$', format(tuition, '8,.2f'))
# get the next studen't name
student_name = infile.readline()
# close the input file
infile.close()
# print the counters and payment total amount
print
print('total number of resident students: ', resident_counter)
print('total number of nonresident: ', nonresident_counter)
print
print('total students: ', end='')
print('$', format(tuition, ',.2f'))
# execute the main function
main()
【问题讨论】:
-
附带说明:在 Python 3 中,单独编写
print本身不会打印空行,它只会查找print函数的值,并且什么也不做。你可能想要print()。此外,您可能想要with open('enroll.txt', 'r') as infile而不是手动调用close;如果您只是在了解try的工作原理,那么您只是在尝试手动清理时遇到麻烦。 -
PS,你从哪里复制代码?如果我们知道您要做什么,我们就可以更好地猜测该怎么做……
-
最后一件事:围绕
readline(f)的显式循环通常值得用for line in f:替换。它更容易阅读,它消除了栅栏错误的可能性等。在您的情况下,您正在处理三行的批次,而不是逐行处理,这使得这变得更加棘手 - 但您可以只做for (student, code, credits) in grouper(3, infile):(请参阅stackoverflow.com/questions/1624883/… 为grouper)。 -
我没有复制这段代码。我为课堂作业写了它,在一遍又一遍地工作后感到沮丧,但它不起作用。
-
那你为什么要添加
try:这一行呢?
标签: python python-3.x