缩进块错误

时间:2012-12-06 02:08:36

标签: python

for line in range(50):
    def show_table():   

        if len(table) == 0: 
            print('There are no cards on the table.')   
        else:
            for card in range(len(table)):
                print names[table[card][0]] + ' played a ' + str(table[card][1]) + '.'

1 个答案:

答案 0 :(得分:1)

第一个问题是冒号在if条件的末尾而不是在if之后。所以:

if len(table) == 0: print('There are no cards on the table.')

或者,更好:

if len(table) == 0:
    print('There are no cards on the table.')

然而,使用Python 2.7和3.3进行测试时,我认为你实际上应该得到一个SyntaxError,小插入指向多余的冒号,而不是关于缩进的错误。

这意味着实际错误是它上面的行也出错了。

下一个问题是你只能使用一个冒号而不是两个冒号,所以这个:

else: for card in range(len(table)): print names[table[card][0]] + ' played a ' + str(table[card][1]) + '.' ?

只会混淆编译器。你真的应该把它分解成惯用的Python,而不是试图看看你能得到什么:

for line in range(50):

    def show_table():
        if len(table) == 0:
            print('There are no cards on the table.')
        else:
            for card in range(len(table)):
                print names[table[card][0]] + ' played a ' + str(table[card][1]) + '.' ?

我不确定你为什么要为50行中的每一行定义一个新函数,然后从不调用该函数,但这至少是合法的...几乎。

最后一个问题是:

print names[table[card][0]] + ' played a ' + str(table[card][1]) + '.' ?

首先,print不是Python 3.3中的语句,它是一个常规的旧函数,所以你必须用参数调用它。其次,最后?似乎并没有附加到它可以合理附加的任何东西上,所以它可能是一个需要修复的流浪错字。所以:

print(names[table[card][0]] + ' played a ' + str(table[card][1]) + '.')

查看您粘贴到已编辑问题中的原始版本 - 这只是猜测,因为您没有将其粘贴为代码 - 看起来可能还有两个问题。

首先,您的第一行for行缩进1列。当你后来回到第0列时,那被视为两个dedents,而不是一个。

其次,def show_table():行缩进到第8列,但接下来就是第0列。也许你想要一个空函数?如果是这样,那是不合法的;在Python中,函数永远不会为空。但是你可以使用pass语句获得相同的效果:

def show_table():
    pass
相关问题