Last active
January 3, 2016 16:19
-
-
Save Kwpolska/8488091 to your computer and use it in GitHub Desktop.
Poor Man’s `for` re-implementation in pure python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### original code: | |
for i in X: | |
if i != 0: | |
print(i) | |
else: | |
break | |
else: | |
print('done, no zeroes') | |
### re-implemented as: | |
_iter = iter(X) | |
_iterating = True | |
while _iterating: | |
try: | |
i = next(_iter) | |
# contents of the for block | |
if i != 0: | |
print(i) | |
else: | |
break # handled by `while` | |
except StopIteration: | |
# contents of the else block, or `pass` | |
print('done, no zeroes') | |
# end the `while` loop (could also use a `break`) | |
_iterating = False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment