简体   繁体   中英

Issue with loop “for if else” python

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

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM