我不知道如何解決這個問題。我試過重新輸入程序。Python意外indentaton錯誤主要()
我得到一個意想不到的縮進錯誤的最後一個主要功能。
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()
作爲一個方面說明:'寫作本身print'不會在Python 3打印一個空行,它會只是仰望的'print'函數的值並沒有採取任何措施。你可能需要'print()'。此外,您可能希望將open('enroll.txt','r')作爲infile'而不是進行手動'close'調用;如果你剛剛學習如何「嘗試」的工作,你只是想要嘗試手動清理的麻煩。 – abarnert
PS,你從哪裏複製代碼?如果我們知道你想要做什麼,我們可以更好地猜測如何去做...... – abarnert
最後一件事:圍繞'readline(f)'的顯式循環通常值得用'for line in f:'替代。它更容易閱讀,它消除了fencepost錯誤的可能性等等。在你的情況下,你處理的是三行的批次,而不是逐行,這使得這更復雜 - 但你可以做'for(student,代碼,學分)在石斑魚(3,infile):'(參見http://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n for'grouper' )。 – abarnert