Boston Python Workshop 8/Loops: Difference between revisions

From OpenHatch wiki
Content added Content deleted
imported>Jesstess
(Created page with "__NOTOC__ == For loops == Use a <code>for</code> loop to do something to every element in a list. <pre> >>> names = ["Jessica", "Adam", "Liz"] >>> for name in names: ... ...")
 
imported>Jesstess
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 8: Line 8:
>>> names = ["Jessica", "Adam", "Liz"]
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
>>> for name in names:
... print name
... print(name)
...
...
Jessica
Jessica
Line 17: Line 17:
>>> names = ["Jessica", "Adam", "Liz"]
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
>>> for name in names:
... print "Hello " + name
... print("Hello " + name)
...
...
Hello Jessica
Hello Jessica
Line 28: Line 28:
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
... if name[0] in "AEIOU":
... if name[0] in "AEIOU":
... print name + " starts with a vowel."
... print(name + " starts with a vowel.")
...
...
Alice starts with a vowel.
Alice starts with a vowel.
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 41: Line 43:
... vowel_names.append(name)
... vowel_names.append(name)
...
...
>>> 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 ===
Line 53: Line 68:
>>> for letter in letters:
>>> for letter in letters:
... for number in numbers:
... for number in numbers:
... print letter * number
... print(letter * number)
...
...
a
a
Line 70: Line 85:
>>> for number in numbers:
>>> for number in numbers:
... for letter in letters:
... for letter in letters:
... print number * letter
... print(number * letter)
...
...
a
a
Line 119: Line 134:
>>> numbers = range(5)
>>> numbers = range(5)
>>> for number in numbers:
>>> for number in numbers:
... print number * number
... print(number * number)
...
...
0
0
Line 132: Line 147:
<pre>
<pre>
>>> for number in range(5):
>>> for number in range(5):
... print number * number
... print(number * number)
...
...
0
0
Line 140: Line 155:
16
16
</pre>
</pre>

== <code>while</code> loops ==

Use a <code>while</code> loop to loop so long as a condition is <code>True</code>.

<pre>>>> i = 0
>>> while i < 10:
... print i
... i = i + 1
...
0
1
2
3
4
5
6
7
8
9</pre>

=== <code>break</code> keyword ===

Use the <code>break</code> keyword to break out of a loop early:

<pre>
>>> i = 0
>>> while True:
... print i
... i = i + 1
... if i > 10:
... break
...
0
1
2
3
4
5
6
7
8
9
10</pre>


=== Get user input with <code>raw_input()</code> ===
=== Get user input with <code>raw_input()</code> ===


<pre>
<pre>
>>> while True:
>>> for i in range(100):
... input = raw_input("Please type something> ")
... input = raw_input("Please type something> ")
... if input == "Quit":
... if input == "Quit":
... print "Goodbye!"
... print("Goodbye!")
... break
... break
... else:
... else:
... print "You said: " + input
... print("You said: " + input)
...
...
Please type something> Hello
Please type something> Hello

Latest revision as of 12:07, 13 July 2013


For loops

Use a for loop to do something to every element in a list.

>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
...     print(name)
...
Jessica
Adam
Liz
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
...     print("Hello " + name)
...
Hello Jessica
Hello Adam
Hello Liz

if statements inside for loop

>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
...     if name[0] in "AEIOU":
...         print(name + " starts with a vowel.")
... 
Alice starts with a vowel.
Ellen starts with a vowel.

Building up a list

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 for loop, and append elements to the new list inside the for loop:

>>> vowel_names = []
>>> for name in ["Alice", "Bob", "Cassie", "Deb", "Ellen"]:
...     if name[0] in "AEIOU":
...         vowel_names.append(name)
... 
>>> print(vowel_names)
['Alice', 'Ellen']

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 for loop that you update inside the for loop:

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

for loops inside for loops

You can put for loops inside for loops. The indentation dictates which for loop a line is in.

>>> letters = ["a", "b", "c"]
>>> numbers = [1, 2, 3]
>>> for letter in letters:
...     for number in numbers:
...         print(letter * number)
...
a
aa
aaa
b
bb
bbb
c
cc
ccc

The order of the for loops matters. Compare the above example with this one:

>>> for number in numbers:
...     for letter in letters:
...         print(number * letter)
...
a
b
c
aa
bb
cc
aaa
bbb
ccc

Useful functions related to lists and for loops

sorting lists

Use .sort() to sort a list:

>>> names = ["Eliza", "Joe", "Henry", "Harriet", "Wanda", "Pat"]
>>> names.sort()
>>> names
['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda']

Getting the maximum and minimum values from a list

>>> numbers = [0, 3, 10, -1]
>>> max(numbers)
10
>>> min(numbers)
-1

Generating a list of numbers easily with range()

The range() function returns a list of numbers. This is handy for when you want to generate a list of numbers on the fly instead of creating the list yourself.

>>> range(5)
[0, 1, 2, 3, 4]

Use range when you want to loop over a bunch of numbers in a list:

>>> numbers = range(5)
>>> for number in numbers:
...     print(number * number)
...
0
1
4
9
16

We could rewrite the above example like this:

>>> for number in range(5):
...     print(number * number)
...
0
1
4
9
16

Get user input with raw_input()

>>> for i in range(100):
...     input = raw_input("Please type something> ")
...     if input == "Quit":
...         print("Goodbye!")
...         break
...     else:
...         print("You said: " + input)
... 
Please type something> Hello
You said: Hello
Please type something> How are you?
You said: How are you?
Please type something> Quit
Goodbye!
>>> 

« Back to the Saturday lecture page