Boston Python Workshop 8/Loops: Difference between revisions

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
Line 140: Line 140:
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