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

Content added Content deleted
imported>Jesstess
imported>Jesstess
Line 511: Line 511:
====if statements====
====if statements====


The simplest way to make a choice in Python is with the <code>if</code> keyword. Here's an example:
The simplest way to make a choice in Python is with the <code>if</code> keyword. Here's an example (don't try to type this one, just look at it for now):


&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
<pre>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code>
if 6 > 5:
print("Six is greater than five!")
</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
That is our first multi-line piece of code, and the way to type it at a Python prompt is a little different. Let's break down how to do this (type this out step by step):


<ol>
<code> if 6 > 5:</code>
<li>First, type the<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
<br />
part, and press Enter. The next line will have <code>...</code> as a prompt, instead of the usual <code>&gt;&gt;&gt;</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.</li>


<li>Press the spacebar 4 times to indent.</li>
part, and press Enter. The next line will have
<li>Type<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code><br /><br /></li>
<li>Press Enter to end the line. The prompt will still be a <code>...</code></li>
<li>Press Enter one more time to tell Python you are done with this code block. The code block will now execute.</li>
</ol>


All together, it will look like this:
<code> ...</code>

as a prompt, instead of the usual <code>&gt;&gt;&gt;</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.

Enter 4 spaces, and then type

<code> print("Six is greater than five!")</code>

Press Enter to end the line, and press Enter again to tell Python you are done with this code block. All together, it will look like this:


<pre>
<pre>