# This is the 'For Else' example fiddle. It is incorrect. print('Original fiddle example') from random import randrange n = 5 foo = [randrange(10) for i in range(n)] for i in foo: if i == 0: print('found 1') else: print('did not find 1') # This is the same thing, without the confounding influence of randomness. It prints both "found" and did not "find". print('Original fiddle example, without randomness') foo = [0, 1, 2, 3, 4, 5] for i in foo: if i == 0: print('found 1') else: print('did not find 1') # This is the the way it should have been written. The else clause of a for loop is taken if and only if the loop exits "naturally", i.e., without a break statement. print('Fixed fiddle example, without randomness') foo = [0, 1, 2, 3, 4, 5] for i in foo: if i == 0: print('found 1') break else: print('did not find 1')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question