为什么我在 python 2.7 中得到 else 语句的语法错误?

时间:2021-01-23 13:43:32

标签: python python-3.x python-2.7

我在 python 3.9 中使用了下面的代码,它运行完全没有问题,但是当我在 2.7 版本中使用它时,它不起作用我重新输入了 5 次代码,但仍然不起作用。它给了我 else 的语法错误

请帮我解决这个问题

for row in range(7):
    for col in range(11):
        if ((col==0 or col==6 or col==10) or (row==3 and col==1))or((row==2) and (col==2 or col==8)) or (row==4 and col==2) or ((row==1) and (col==3 or col==7 or col==9)) or (row==5 and col==3) or ((row==0 or row==6) and (col==4)):
            print("*",end="")
else:
print(end=" ")
    print()

4 个答案:

答案 0 :(得分:2)

print("something") 是 python3 的语法。

在python2中,它是print "something"


在代码的第一行添加如下代码,然后就可以在python2.7中使用print(...)

from __future__ import print_function

答案 1 :(得分:1)

python2 和 python3 之间有一些语法不同。 并非所有 python2 代码都使用 python3 正确运行。例如在打印命令中。

答案 2 :(得分:0)

可能在 "else:" 之后缩进 print(end=" ")

答案 3 :(得分:0)

您应该正确对齐下面语句下面的代码行:

for row in range(7):
    for col in range(11):
        if ((col==0 or col==6 or col==10) or (row==3 and col==1))or((row==2) and (col==2 or col==8)) or (row==4 and col==2) or ((row==1) and (col==3 or col==7 or col==9)) or (row==5 and col==3) or ((row==0 or row==6) and (col==4)):
            print("*",end="")
else:
  print(end=" ")
  print()