Boston Python workshop 2/Friday tutorial: Difference between revisions

Content added Content deleted
No edit summary
Line 327: Line 327:


==Booleans==
==Booleans==

So far, the code we've written has been <i>unconditional</i>: no choice is getting made, and the code is always run. Python has another data type called a <b>boolean</b> that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>:


<pre>
<pre>
Line 343: Line 345:
type(False)
type(False)
</pre>
</pre>

You can test if Python objects are equal or unequal:


<pre>
<pre>
Line 351: Line 355:
0 == 1
0 == 1
</pre>
</pre>

Use <code>==</code> to test for equality. Recall that <code>=</code> is used for <i>assignment</i> (e.g. <code>my_string == "Hello"</code>).

<code>=</code> is assignment, <code>==</code> is comparison.

Use <code>!=</code> to test for inequality:

<pre>
"a" != "a"
</pre>

<pre>
"a" != "A"
</pre>

<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class:

<pre>
1 > 0
</pre>

<pre>
2 >= 3
</pre>

<pre>
-1 < 0
</pre>

<pre>
.5 <= 1
</pre>

You can check for containment with the <code>in</code> keyword:


<pre>
<pre>
Line 358: Line 396:
<pre>
<pre>
"X" in "Hello"
"X" in "Hello"
</pre>

Or check for a lack of containment with <code>not in</code>:

<pre>
"Elvis" not in "Elvis has left the building"
</pre>
</pre>