User:Sybren/SfA/for-vs-while
< User:Sybren | SfA
Scripting for Artists: for
vs. while
& control statements
Prerequisite: Collections API
Chapter 3: Stuff on Lists showed for
-loops.
Tweet by Rodger:
- I see you have "For" loops. When is it better to use "While" loops instead?
Differences
For:
for
: iterates over 'iterable', 'iterable' is something you can iterate over.- To iterate = to repeat. In Python it often means asking 'Next, please?'.
- There can be an end to the iteration, or it can be infinite (f.e. 'all odd numbers greater than five').
While:
while
: also repeats, while the condition is true.- Does not ask 'next, please', but asks 'should I keep going?'
- One can be transformed into the other.
Changing while you loop:
for
: important to not change the thing you iterate over (SfA chapter 3: Stuff on Lists).while
: investigates every time, so things can change.
Reasons for while
- Unknown end of the loop:
- "while the network connection is open".
- "while the parent is not
None
".
- do/while construct, do it once, repeat if necessary.
- Changing what we're looping over.
- while queue not empty
== Controlling the Loops
continue
: to skip the rest of the loop body, and continue with the next iteration.break
: to skip everything and continue after the loopfor/else
: for finding things
Behind the scenes of for
(not included in the video)
names = ['Rain', 'Spring', 'Dixey', 'Hendrik']
for name in names:
print(f'Name is: {name}')
# unrolls to:
iterator = iter(names)
while True:
try:
name = next(iterator)
except StopIteration:
break
print(f'Name is: {name}')