for i in range(3): print(i) else: print('Done')
The else block after a for loop runs only if the loop finishes all iterations without a break.
Here, the loop prints 0, 1, 2 and then the else prints 'Done'.
for i in range(5): if i == 2: break print(i) else: print('Finished')
The loop breaks when i == 2, so it prints 0 and 1 only.
The else block is skipped because of the break.
The else block runs only if the loop finishes normally without encountering a break.
If break is used, else is skipped.
for x in range(2): for y in range(3): if y == 1: break print(f'{x},{y}') else: print('Inner else') else: print('Outer else')
The inner loop breaks when y == 1, so inner else is skipped both times.
The outer loop completes normally, so outer else runs.
d after executing this code?d = {}
for i in range(5):
if i == 3:
break
d[i] = i * 2
else:
d['done'] = True
print(len(d))The loop breaks when i == 3, so only keys 0,1,2 are added.
The else block is skipped, so 'done' key is not added.
Length is 3.
