Boston Python Workshop 4/ColorWall handout: Difference between revisions

From OpenHatch wiki
Content added Content deleted
imported>Jesstess
(UrZUtGcnICNrZi)
 
(6 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Thanks for saihnrg. Always good to find a real expert.
====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 everything you want to be run if the if
conditional is <code>True</code>. For example:

<pre>
>>> James = 35
>>> Alice = 30
>>> if James > Alice:
... print "James is older than Alice."
...
James is older than Alice.
>>></pre>

Because James really is older than Alice, the <code>if</code> conditional is <code>True</code>,
so Python does execute the code indented under the if line. In this
case we print "James is older than Alice."

<pre>
>>> James = 35
>>> Alice = 30
>>> if James < Alice:
... print "James is younger than Alice."
...
>>></pre>

Because James is not older than Alice, the <code>if</code> conditional is <code>False</code>, 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:

<pre>
>>> names = ["Jessica", "Adam", "Liz"]
>>> for name in names:
... print "Hello", name
...
Hello Jessica
Hello Adam
Hello Liz</pre>

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.

====Range====

<pre>
>>> range(5)
[0, 1, 2, 3, 4]
>>> for i in range(5):
... print "Hi" * i
...

Hi
HiHi
HiHiHi
HiHiHiHi</pre>

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

<pre>
>>> for i in range(80):
... if i % 9 == 0:
... print i, "is divisible by 9."
...
0 is divisible by 9.
9 is divisible by 9.
18 is divisible by 9.
27 is divisible by 9.
36 is divisible by 9.
45 is divisible by 9.
54 is divisible by 9.
63 is divisible by 9.
72 is divisible by 9.</pre>

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

<pre>
>>> 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
>>> for number in numbers:
... for letter in letters:
... print number * letter
...
a
b
c
aa
bb
cc
aaa
bbb
ccc</pre>

Latest revision as of 21:29, 15 January 2012

Thanks for saihnrg. Always good to find a real expert.