Boston Python Workshop 3/Friday/Tutorial: Difference between revisions

Content added Content deleted
imported>Jesstess
No edit summary
imported>Jesstess
Line 575: Line 575:
====more choices: <code>if</code> and <code>else</code>====
====more choices: <code>if</code> and <code>else</code>====


You can use the <code>else</code> keyword to conditionally execute code when the expression for the <code>if</code> block isn't true:
You can use the <code>else</code> keyword to execute code only when the <code>if</code> expression isn't true:


<pre>
<pre>
Line 587: Line 587:


Like with <code>if</code>, the code block under the <code>else</code> statement must be indented.
Like with <code>if</code>, the code block under the <code>else</code> statement must be indented.

====even more choices: <code>elif</code>====

If you have more than two cases, you can use the <code>elif</code> keyword to check more cases. You can have as many <code>elif</code> cases as you want; Python will go down the code checking each <code>elif</code> condition until it finds a true condition or reaches the default <code>else</code> block.

<pre>
sister_age = 15
brother_age = 12
if sister_age > brother_age:
print "sister is older"
elif sister_age == brother_age:
print "sister and brother are the same age"
else:
print "brother is older"
</pre>

You don't have to have an <code>else</code> block, if you don't need it:

<pre>
color = "orange"
if color == "green" or color == "red":
print "Christmas color!"
elif color == "black" or color == "orange":
print "Halloween color!"
elif color == "pink":
print "Valentine's Day color!"
</pre>


====compound conditionals: <code>and</code> and <code>or</code>====
====compound conditionals: <code>and</code> and <code>or</code>====