【问题标题】:Python unexpected indentaton error main()Python 意外缩进错误 main()
【发布时间】: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


【解决方案1】:

您在 if else 语句中混合了房间类型和代码类型。您还缺少您的 except 声明。这应该是调用 main 之前的最后两行。

应该是:

except IOError:
    print('an error occurred trying to open or read enroll.txt')

【讨论】:

  • 感谢您的帮助。缩进错误已修复。我会尽量自己完成剩下的课程。
【解决方案2】:

除了缺少的exceptfinally 或额外的try...如果你看一下edited code,你可以看到压痕中奇怪的混合色块。这意味着您正在混合制表符和空格,这可能会导致缩进错误等问题。原因是解释器对如何解释制表符有不同的看法(例如 8 列与 4 列制表位)。

您不能在缩进中混合使用制表符和空格。我个人建议只使用空格。任何体面的编辑器都能够将 TAB 键扩展到空格和/或取消制表符和空格的现有混合。

【讨论】:

    【解决方案3】:

    其他答案(正确地)指出您需要有一个 except 才能与您的 try: 一起使用(或者完全不使用 try)。我要去try 解释你以后如何去调试类似的问题,因为这些调试起来很烦人。

    您的错误消息很可能是这样的:

      File "test.py", line 74
        main()
        ^
    IndentationError: unexpected unindent
    

    乍一看,这似乎没有太大帮助,而且肯定不是很清楚。

    您“尝试重新键入程序”的事实听起来就像您看到 IndentationError 并认为,“这意味着我的缩进搞砸了;也许某处有多余的空格,或者空格和制表符的混合或其他东西。”这些绝对是有效的IndentationErrors,如果你没有再次犯同样的打字错误,重新输入程序会修复它们。 (附带说明一下,我相信任何值得使用的文本编辑器都可以选择将所有制表符转换为 4 个空格,以避免很多缩进问题。)

    但是,查看错误文本,我们看到“意外取消缩进”。对我来说,这听起来有点像胡言乱语,但它的意思是,当 python 查看你的程序时,它遇到了它认为应该缩进更多的行。 (不幸的是,这种错误可以称为“意外的未缩进”或“预期的缩进块”,甚至可以显示为普通的旧SyntaxError: invalid syntax。)

    所以知道错误消息的含义后,我们可以回顾一下代码,看看为什么 python 认为 main() 缩进很奇怪——尽管我们必须小心,因为 python 并不总是正确地知道问题的实际出在哪里.这将是我的思考过程:

    • 在调用main() 之前有一个函数定义,也许该函数希望main() 在其中?不,不是这样,因为 python 只希望在函数定义之后至少有一行代码。
    • 还有什么“希望”代码在其后缩进? ifelifwhile 都可以,但它们后面都有代码。
    • 唯一的其他“压头”是try:。此时,您要么知道 try: needs to be followed by a except: or a finally: 并修复它,要么不知道。如果您不知道这一点,您仍然可以看到try: 后面跟着一个缩进块,并且鉴于它可能是您错误的罪魁祸首,决定是时候查找try: 的作用了。

    我希望这有助于将来解决此类问题,并查看 abarnert 的答案和我的链接,了解更多关于使用 try/except/else/finally 语句处理错误的信息。

    【讨论】:

      【解决方案4】:

      尽管其他人都这么说,如果您有try,则不必有except:您必须有except finally

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

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

      【讨论】:

        【解决方案5】:

        您正在使用 try 语句。这意味着你必须有一个 except 块

        try:
            some code
        except:
            pass
        

        这是简化,但会解决您的问题。

        【讨论】:

        • 正如我在另一个答案上所说:“except: pass 基本上意味着如果try: 代码块中的任何地方出现问题,您什么也不做,而不是处理错误。您通常不不想使用except: pass,尤其是作为缩进问题的“修复”。”
        • 当然,但是要向一个新的 python 人解释一下,可以使用它(恕我直言)。
        【解决方案6】:
        1. 正如上面 LevLevitsky 和 ​​david 所指出的,没有 except 子句。解决这个问题的最简单方法是在调用 main 之前在代码中添加如下一行:

          except: pass
          
        2. 我对您的代码的第二条评论更具风格,但您可以在调用 main 之前和 except 子句之后添加以下内容:

          if __name__ == '__main__':
              main()
          

        【讨论】:

        • except: pass 基本上意味着如果try: 代码块中的任何地方出现问题,您什么都不做,而不是处理错误。您通常不想使用except: pass,尤其是作为缩进问题的“修复”。
        • @MatthewAdams 这是“解决这个问题的最简单方法”,不是最好的,也不是推荐的方法。
        • 对,但我想向阅读本文的新用户说明这一点。
        • @MatthewAdams 你真的应该投票否决我的回答。我会这样做,但我不会这样做。
        • 也许吧,但如果你不知道它是什么,你永远不会通过默默地丢弃异常来弄清楚它;最好让它提高,看看需要做什么。 (PS,你怎么知道try子句的原因不是finally而不是except?)
        【解决方案7】:

        您没有与try 匹配的except 子句。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-14
          • 2020-12-17
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          • 2011-04-24
          • 2018-06-11
          相关资源
          最近更新 更多