Boston Python workshop 2/Friday tutorial: Difference between revisions
Content added Content deleted
Line 413: | Line 413: | ||
<pre> |
<pre> |
||
if |
if True: |
||
print " |
print "I'm True!" |
||
</pre> |
</pre> |
||
That was our first multi-line piece of code, and the way to enter it at a Python prompt is a little different. First, type the <code>if |
That was our first multi-line piece of code, and the way to enter it at a Python prompt is a little different. First, type the <code>if True:</code> part, and hit enter. The next line will have <code>...</code> as a prompt, instead of the usual <code>>>></code>. This is Python telling us that we are in the middle of a <b>code block</b>, and so long as we indent our code it should be a part of this code block. |
||
Type 4 spaces, and then type <code>print " |
Type 4 spaces, and then type <code>print "I'm True!"</code>. Hit enter to end the line, and hit enter again to tell Python you are done with this code block. All together, it will look something like this: |
||
<pre> |
<pre> |
||
>>> if |
>>> if True: |
||
... print " |
... print "I'm True!" |
||
... |
... |
||
"I'm True!" |
|||
⚫ | |||
</pre> |
</pre> |
||
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. |
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 " |
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? |
||
<pre> |
|||
if False: |
|||
print "I'm True!" |
|||
</pre> |
|||
<pre> |
|||
What about a 0? Is it truthy? |
|||
if 1: |
|||
⚫ | |||
</pre> |
|||
<pre> |
<pre> |