else/QuickTips/continue.md

78 lines
1.5 KiB
Markdown
Raw Normal View History

2016-05-10 08:00:29 +00:00
Continue
========
2017-02-19 01:06:55 +00:00
Skips the rest of the current iteration, and starts the next one.
```Python
>>> for x in range(6):
... if x == 3:
... continue
... print(x)
...
0
1
2
4
5
```
```Python
while len(directory_queue) > 0:
directory = directory_queue.popleft()
try:
filenames = os.listdir(directory)
except PermissionError:
continue
for filename in filenames:
...
```
2016-05-10 08:00:29 +00:00
2017-04-08 00:11:22 +00:00
#### Continue is great for cleaning code with lots of conditions:
2016-05-10 08:00:29 +00:00
2017-04-08 00:11:22 +00:00
##### Without continue:
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
Nested:
```Python
for submission in submissions:
if submission.author is not None:
if not submission.over_18:
if 'suggestion' in submission.title.lower():
print('Found:', submission.id)
```
or all grouped up:
```Python
for submission in submissions:
if (
submission.author is not None
and not submission.over_18
and 'suggestion' in submission.title.lower()
):
print('Found:', submission.id)
```
2016-05-10 08:00:29 +00:00
2017-04-08 00:11:22 +00:00
##### With continue:
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
```Python
for submission in submissions:
if submission.author is None:
continue
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
if submission.over_18:
continue
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
if 'suggestion' not in submission.title.lower():
continue
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
print('Found:', submission.id)
```
2016-05-10 08:00:29 +00:00
2017-02-19 01:06:55 +00:00
Notice that all of the checks are the opposite of the originals. The mentality changes from "keep only the items with the right properties" to "discard the items with the wrong properties", and the result is the same.