首页 > 解决方案 > 克服 Python 中的缩进错误的标准做法是什么

问题描述

每当我尝试使用一些 if 语句编写嵌套 for 循环时,我都是 Python 新手,但我遇到了这个缩进错误。如果不使用其他编程语言使用的命令 END,我很想知道块的开始和块在哪里结束,以及 python 如何识别它。下面是我的示例代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as im



img = im.imread('OD6.jpg')
plt.imshow(img)
plt.show()

R=img[:,:,0]
G=img[:,:,1]
B=img[:,:,2]


M,N=R.shape

gray_img= np.zeros((M,N))
intensity= np.zeros((M,N))

for i in range(M):
        for j in range(N):
            gray_img[i, j]=(R[i, j]*0.2989)+(G[i, j]*0.5870)+(B[i, j]*0.114);

t=127


for i in range(1, M-1):
    for j in range(1, N-1):
        intensity[i,j]=gray_img[i,j]

标签: python

解决方案


如果我理解正确,这不是 Spyder,而是 Python 相关问题。正如评论中所指出的,您可以在此处找到官方文档

而在Java你会有这样的事情:

for(int i, i<100, i++) {
[...]
}

中的所有内容都在{..}循环内,Python缩进级别显示其关联。

for i in range(100):
    #Indent by one tab belongs to the loop
    [...] 
#Everything 'unindented' afterwards, is outside of the loop

另一个例子

#Function A is defined
def A():
    #Indented stuff is within the function
    [...]
    for i in range(100):
        #Everything indented twice is within the loop
        [...]
    #Here we are outside the loop, but inside the function

#Here we are outside the function and can call it
x = A()

推荐阅读