[英]Python indentation error in code
Please, firstly, is there an IDE where indentation is being taken care of? 首先,请问有一个IDE可以处理缩进吗? secondly, I have an indentation error in my code.
其次,我的代码中存在缩进错误。 Could anyone point out where the indentation is needed in my code?
谁能指出我的代码中需要缩进的地方?
p = [0.2,0.2,0.2,0.2,0.2]
world = ['green','red','red','green','green']
z = 'red'
pHit = 0.6
pMiss = 0.2
def sense(p, z):
q=[]
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q
print sense(p,z)
return
doesn't seem to be in the right place. return
似乎不在正确的位置。 But, you can re-indent your code: 但是,您可以重新缩进代码:
p = [0.2,0.2,0.2,0.2,0.2]
world = ['green','red','red','green','green']
z = 'red'
pHit = 0.6
pMiss = 0.2
def sense(p, z):
q=[]
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q # dedented
print sense(p,z)
In python you can use tabs or spaces as indentation, but you must remain consistent in what you use and how many of them there are. 在python中,您可以使用制表符或空格作为缩进,但必须保持一致,无论使用什么或使用多少。 Take a closer look at the following:
仔细看看以下内容:
def sense(p, z):
q=[]
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q
Whether or not the return statement is where it belongs, the issue is with the lines 不管return语句是否属于它,问题在于行
q=[]
for i in range(len(p)):
relative to 关系到
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q
Notice how there are TWO spaces before the first two lines mentioned and SIX spaces before the body of the for loop. 请注意,在前面提到的前两行之前有两个空格,在for循环的主体之前有六个空格。 Every indentation level should be a multiple of a single indent.
每个缩进级别应为单个缩进的倍数。 So if you want to use two spaces:
因此,如果要使用两个空格:
def sense(p, z):
q=[]
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q
and if you want to use four spaces: 如果要使用四个空格:
def sense(p, z):
q=[]
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i]*(hit*pHit + (1-hit)*pMiss))
return q
I typically go with four and set up my environment to map the tab character to four spaces. 我通常使用四个,并设置环境以将制表符映射到四个空格。
That said...I too agree on moving the return statement. 话虽如此...我也很同意搬回申报单。 But at least now you can run your code and figure out if/why you want to move it.
但是至少现在您可以运行代码并确定是否/为什么要移动它。
You should probably read through all of PEP-8 , but particularly the section on indentation 您可能应该通读所有PEP-8 ,尤其是缩进部分
Your return
statement is not in the right place. 您的
return
单不在正确的位置。 Additionally, pHit
, pMiss
and world
variables should be defined in a function scope: 此外,应在函数范围内定义
pHit
, pMiss
和world
变量:
def sense(p, z):
pHit = 0.6
pMiss = 0.2
world = ['green','red','red','green','green']
q = []
for i in range(len(p)):
hit = (z==world[i])
q.append(p[i] * (hit * pHit + (1 - hit) * pMiss))
return q
p = [0.2,0.2,0.2,0.2,0.2]
z = 'red'
print sense(p,z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.