Python意外的indentaton错误main()

Dav*_*man 3 python python-3.x

我不知道如何解决这个问题.我试过重新输入程序.

我的最后一个主函数出现了意外的缩进错误.

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()
Run Code Online (Sandbox Code Playgroud)

Lev*_*sky 6

你没有except匹配的条款try.


aba*_*ert 5

不管其他人怎么说,如果你有一个try,你就不except必有一个:你必须有一个except 或一个finally

这可能看起来很挑剔,但是您正在复制的代码实际上正在使用是非常合理的finally(例如,为了确保某些清理代码始终运行——假设它正在执行 C-/Java 风格的手动清理)。

无论如何,添加except子句并不是正确的答案。如果您实际上希望处理或忽略错误,那么是的,添加一个except子句。如果您正在寻找添加即使出现错误也能运行的清理代码的地方,请改为添加finally子句。如果您不想要,只需删除该try行。