Boston Python Workshop 8/Loops: Difference between revisions

no edit summary
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
Line 140:
16
</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> ===
 
<pre>
>>> whilefor Truei in range(100):
... input = raw_input("Please type something> ")
... if input == "Quit":
... print ("Goodbye!")
... break
... else:
... print ("You said: " + input)
...
Please type something> Hello
Anonymous user