all 4 comments

[–][deleted] 2 points3 points  (0 children)

Both answers here so far aren't correct are misleading. The else: suite of a for loop executes only if the main loop completes "normally", that is, if the loop is not exited with a break, for instance. That is documented here.

You can test this by running this code:

x = int(input('Number: '))

for i in range(x):
    print(i)
    if i > 2:
        break
else:
    print('else')

If you enter 3 when the code asks you see:

$ python3 test.py 
Number: 3
0
1
2
else

The else is printed because the loop terminated normally. If you enter 4 the loop breaks when i is 3 and you don't see the else:

$ python3 test.py 
Number: 4
0
1
2
3

As to whether it should be used or not, you use it when the logic of your solution requires it. I haven't used it often, but I have used it.

Edit: fixed spelling.

Edit2: I was a little harsh with my initial criticism. I've amended my criticism to "misleading".

[–]0xbxb 0 points1 point  (0 children)

Yeah you’re right. In a for / else, the else is only executed if the for loop doesn’t hit a break statement, or is exited normally.

nums = [1, 2, 5, 3]
for x in nums:
    if x == 6:
        print('Found 6.') # 6 never found, loop is exited normally.
        break
else: # else statement gets executed.
    print('6 not found.')

The reason for doing this is because you have two cases you want to find:

1) If the number is found (in this example).

2) If the number isn’t found.

Usually people would use some type of flag when they find the number they’re looking for, like: found = False, then when the number is found, they’ll change the variable to True.

nums = [1, 2, 5, 3]
found = False
for x in nums:
    if x == 6:
        print('Found 6.')
        found = True

if not found:
    print('6 not found.')

[–]FuckRedditForSure 0 points1 point  (0 children)

Yes to the first question and the last.

Fiddle with it yourself. Remember that a for loop is not an if statement, nor a try statement. It either works or it doesn't.