Boston Python Workshop 4/ColorWall handout: Difference between revisions
Content added Content deleted
imported>Jesstess (Created page with '====Indentation reminder==== In Python, indentation matters. Everything is indented by a multiple of some number of spaces, often 4. In <code>if</code> statements, you indent e…') |
imported>Jesstess No edit summary |
||
Line 45: | Line 45: | ||
The <code>print</code> line is indented 4 spaces under the <code>for</code>. That's how |
The <code>print</code> line is indented 4 spaces under the <code>for</code>. That's how |
||
Python knows to execute the print line for every name in names. |
Python knows to execute the print line for every name in names. |
||
====Range==== |
|||
<pre> |
|||
>>> range(5) |
|||
[0, 1, 2, 3, 4] |
|||
>>> for i in range(5): |
|||
... print "Hi" * i |
|||
... |
|||
Hi |
|||
HiHi |
|||
HiHiHi |
|||
HiHiHiHi</pre> |
Revision as of 03:11, 30 September 2011
Indentation reminder
In Python, indentation matters. Everything is indented by a multiple of some number of spaces, often 4.
In if
statements, you indent everything you want to be run if the if
conditional is True
. For example:
>>> James = 35 >>> Alice = 30 >>> if James > Alice: ... print "James is older than Alice." ... James is older than Alice. >>>
Because James really is older than Alice, the if
conditional is True
,
so Python does execute the code indented under the if line. In this
case we print "James is older than Alice."
>>> James = 35 >>> Alice = 30 >>> if James < Alice: ... print "James is younger than Alice." ... >>>
Because James is not older than Alice, the if
conditional is False
, so
Python does not execute the code indented under the if line.
In for loops, you indent everything you want to be run each loop For example:
>>> names = ["Jessica", "Adam", "Liz"] >>> for name in names: ... print "Hello", name ... Hello Jessica Hello Adam Hello Liz
The print
line is indented 4 spaces under the for
. That's how
Python knows to execute the print line for every name in names.
Range
>>> range(5) [0, 1, 2, 3, 4] >>> for i in range(5): ... print "Hi" * i ... Hi HiHi HiHiHi HiHiHiHi