Boston Python workshop 2/Friday tutorial: Difference between revisions

Line 430:
So what is going on here? When Python encounters the <code>if</code> keyword, it <i>evaluates</i> the <i>expression</i> following the keyword and before the colon. If that expression is <b>True</b>, Python executes the code in the indented code block under the <code>if</code> line. If that expression is <b>False</b>, Python skips over the code block.
 
In this case, because <code>1</code> is truthy, Python executes the code block under the if statement, and we see "I'm True!" printed to the screen. What do you think will happen here?with this one:
 
<pre>
Line 455:
if "":
print "empty strings are truthy"
</pre>
 
You can use the <code>else</code> keyword to conditionally execute code when the expression for the <code>if</code> block isn't true:
 
<pre>
sister_age = 15
brother_age = 12
if sister_age > brother_age:
print "Sister is older"
else:
print "brother is older"
</pre>
 
You can check multiple expressions together using the <code>and</code> and <code>or</code> keywords. If two expressions are joined by an <code>and</code>, they <b>both</b> have to be True for the overall expression to be True. If two expressions are joined by an <code>or</code>, as long as <b>one</b> is True, the overall expression to be True.
 
<pre>
1 > 0 and 1 < 2
</pre>
 
<pre>
1 < 2 and "x" in "abc"
</pre>
 
<pre>
"a" in "hello" or "e" in hello"
</pre>
 
<pre>
1 < 0 or "x" in "abc"
</pre>
 
<pre>
hour = 11
if hour < 7 or hour > 23:
print "Go away!"
print "I'm sleeping!"
else:
print "Welcome to the cheese shop!"
print "Can I interest you in some choice gouda?"
</pre>
 
Anonymous user