Boston Python Workshop 8/Loops: Difference between revisions

Content added Content deleted
imported>Jesstess
No edit summary
imported>Jesstess
No edit summary
 
Line 33: Line 33:
Ellen starts with a vowel.</pre>
Ellen starts with a vowel.</pre>


=== Building up a list ===
Sometimes you want to start with a new empty list, and only add to that list if some condition is true:

Sometimes you want to build up a new list based on information about each element in an existing list. To do this, initialize an empty list before the <code>for</code> loop, and append elements to the new list inside the <code>for</code> loop:


<pre>
<pre>
Line 43: Line 45:
>>> print(vowel_names)
>>> print(vowel_names)
['Alice', 'Ellen']</pre>
['Alice', 'Ellen']</pre>

=== Using a counter ===

Sometimes you want to keep track of the number of occurrences of something, or a running total, as you loop through a list. To do this, initialize a variable before the <code>for</code> loop that you update inside the <code>for</code> loop:

<pre>
>>> prices = [1.5, 2.35, 5.99, 16.49]
>>> total = 0
>>> for price in prices:
... total = total + price
...
>>> total
26.33</pre>


=== <code>for</code> loops inside <code>for</code> loops ===
=== <code>for</code> loops inside <code>for</code> loops ===