0

I have a problem in the following code:

for n in range(0,i)+range(i+1,len(XY_pos)): # excludes i==n
    if distance(XY_temp,i,n)<sigma:
        XY_temp[i]=XY_pos[i] # back to before the move
        break
else:
    XY_pos[i]=XY_temp[i] # move accepted
    accepted_moves+=1
    NUMBER.append(number(r))
    # overlap condition

This part of code is a codition to make or not a move with my particle located in XY_temp[i]. I tried this structure with something easier and it seemed to work, but not here. I don't have any error message, but I can see in the results that the part after the else is never executed even when it should be. I someone could think of a explanation, it would be warlmy welcome

I'm really new in Python, so I hope it's not a silly question, but after hours looking in the net and by myself to find a solution, I ask here.

I tried with the break at the same level of identation as the "if", and it doesn't seems to change anything.

Thank you

GoBusto
  • 4,632
  • 6
  • 28
  • 45
Mathis
  • 1
  • 1

4 Answers4

0

You have to indent the else part.currently the script is treating it as a part of the for loop.

for n in range(0,i)+range(i+1,len(XY_pos)): # excludes i==n
    if distance(XY_temp,i,n)<sigma:
        XY_temp[i]=XY_pos[i] # back to before the move
        break
    else:
        XY_pos[i]=XY_temp[i] # move accepted
        accepted_moves+=1
        NUMBER.append(number(r))
        # overlap condition
Himal
  • 1,351
  • 3
  • 13
  • 28
0

You need to indent your entire else clause and body one level deeper. Otherwise you have a "for-else" construct instead of an "if-else" inside a "for" loop. The "for-else" is a bit of a Python oddity, but it does exist and you don't want it here.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

Python is very strict on indentation : indentation is the structure of code.

As written, the else is not related to the if but to the for (same level). So you should pass on the else branch only if there was no I to iterate the for loop.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

There is no for-if-else loop, but only for-else loop in python. The if inside is separate statement.

The for-else loop in python is a little tricky:

for i in something:
    <inside code>
else:
    <else code>

the <else code> is executed ONLY IF the whole loop finished without a break or an exception. That means that whenever the <inside code> issues a break or raises an exception, the whole loop just ends and <else code> will not be executed.

It's important to understand that the else branch is tied with the for loop, and not the if inside the loop.

For more information, see: https://wiki.python.org/moin/ForLoop

Jan Spurny
  • 5,219
  • 1
  • 33
  • 47