这是我的代码
#Chose Grid size
m = int(input("Enter the width and length of the Grid: ",))
n = m
print("Your Grid will be",m,"x",n)
Grid = np.zeros((m+2,n+2))
#Grid filling in
i = 0
while(i <= 5*m):
i = i+1
Grid[randint(1,m), randint(1,n)] = 1
img = pl.imshow(Grid, cmap = 'PuRd', interpolation = 'none')
SecGrid = np.zeros((m+2,n+2))
SecGrid = Grid
#Main
for i in range(1,m):
for j in range(1,n):
#Nbr of entities
nbr = 0
for k in range(-1,1):
for l in range(-1,1):
nbr = nbr + Grid[i+k,j+l]
#cells that are alive
if Grid[i,j] == 1:
if nbr > 1 and nbr < 4:
then SecGrid[i,j] = 1
else SecGrid[i,j] = 0
#cells that are dead
else:
if nbr == 3:
then SecGrid[i,j] = 1
else SecGrid[i,j] = 0
这是我的错误
File "/Users/tryotest/Downloads/GameOfLife.py", line 32
then SecGrid[i,j] = 1
^
SyntaxError: invalid syntax
答案 0 :(得分:4)
if foo:
then
是不正确的Python语法。删除then
。
它应该看起来像
if foo:
dosomething
else:
dosomethingelse
答案 1 :(得分:0)
正如错误(SyntaxError
)所示,您的语法错误。在Python中,if语句构造为if ... else ...
有关if语句的更多信息,请单击链接。
https://docs.python.org/2/tutorial/controlflow.html
更一般地说,我建议阅读Python的一般教程,以便掌握整体语法。
答案 2 :(得分:0)
您执行if...else
错误。这是更正后的代码:
#Chose Grid size
m = int(input("Enter the width and length of the Grid: ",))
n = m
print("Your Grid will be",m,"x",n)
Grid = np.zeros((m+2,n+2))
#Grid filling in
i = 0
while(i <= 5*m):
i = i+1
Grid[randint(1,m), randint(1,n)] = 1
img = pl.imshow(Grid, cmap = 'PuRd', interpolation = 'none')
SecGrid = np.zeros((m+2,n+2))
SecGrid = Grid
#Main
for i in range(1,m):
for j in range(1,n):
#Nbr of entities
nbr = 0
for k in range(-1,1):
for l in range(-1,1):
nbr = nbr + Grid[i+k,j+l]
#cells that are alive
if Grid[i,j] == 1:
if nbr > 1 and nbr < 4:
SecGrid[i,j] = 1
else:
SecGrid[i,j] = 0
#cells that are dead
else:
if nbr == 3:
SecGrid[i,j] = 1
else:
SecGrid[i,j] = 0