For and While Loops
- VC Healy
- May 24, 2020
- 2 min read
The for statement iterates over items of any sequence (list, string) as they appear in the sequence
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
Th e simplest way to modify a collection, like words above would be to create a new collection from the previous collection. A example below would be iterating over a list of active/inactive users.
The first option deleting a user that as a key value of status set to inactive.
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
The next code snippet would be preferred over the above code.
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
While Loops
Similar to the for loop only as far as a part of the code is being looped over. This time the loop does not continue to repeat based on the number of elements in an sequence but it is based on a statement remaining true. This can be something as simple as a comparison of a value that changes during each loop with a static value.
The Fibonacci series is an excellent basis to provide an example of this.
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2_000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
As can be seen above code. The function fib() is being called and supplies the agrument 'n' with a parameter of 2000.
In the while loop the value of 'a' is being used to determine when the loop should terminate and once 'a' is equal or greater than this value of 'n', then the loo[p terminates and the print function is actioned.
Comments