Comparisons

Do you still remember what an operator is?

In our homework, we learned some basic arithmetic operators. When we add one more (//), our list will look like this:

Symbol Example Description
+, -, *, / 1 + 1 Basic arithmetic
- -5 Negation
//; % 7 // 2; 7 % 2 Integer division, remainder
** 3 ** 2 Power (3 to the power of 2)

Python also has other types of operators. Comparison (relational) operators are used to compare values. Try out what they do! (You can try them by using print() in your code, or you can try python's command line.)

Symbol Example Description
==, != 1 == 1, 1 != 1 equal, not equal
<, > 3 < 5, 3 > 5 greater than, less than
<=, >= 3 <= 5, 3 >= 5 Greater or equal, less or equal

Comparison values are called boolean values (after G. Boole). They are used every time we want to know if something is True or False. Boolean types are exactly those two - True and False.

Like all values, True and False can be assigned to variables:

true = 1 < 3  # we have to type it in lowercase now, because True is a reserved word in Python
print(true)

false = 1 == 3
print(false)

Note that to test equality, you have to use two equal signs: 3 == 3. One equal sign assigns a value to a variable, and two equal signs compare two values (of variables).

True and False can be used directly in a program. Just keep an eye on capitalisation.

print(True)
print(False)

Conditions

Write the following into a new file (e.g. if.py):

side = float(input('Enter the side of a square in centimeters: '))
print("The perimeter of a square with a side of", side,"cm is ", side * 4,"cm.")
print("The area of a square with a side of", side,"cm is", side * side, "cm2.")

What happens when you enter a negative number? Does the output make sense?

As we can see, the computer does exactly what it is told and doesn't think about context. You have to do that for it. It would be nice if the program could tell the user who enters a negative number that they entered nonsense. How do we do that?

Let’s try to set a variable that will be True when a user enters a positive number.

Řešení

And then we will tell the program to use this variable. For that purpose we will use the if and else statements.

side = float(input('Enter the side of a square in centimeters: '))
positive_number = side > 0


if positive_number:
    print("The perimeter of a square with a side of", side,"cm is", side * 4,"cm.")
    print("The area of a square with a side of", side,"cm is", side * side, "cm2.")
else:
    print("The side must be a positive number!")

print("Thank you for using the geometric calculator.")

So after if, there is a condition which is the expression we'll use for the decision making. After the condition you must write a colon (:). The colon is followed by the commands to be executed, if the condition is True. Indent the lines 4 spaces after every colon you use in Python.

Then on the same level as if, write else: followed by a colon. The next lines contain the commands that are executed if the condition is False, and they must also be indented.
Then you can write other code, not indented, that will be executed every time, because the if statement has already ended.

The indentation doesn't need to be 4 spaces, you could use 2 or even 11, or you can use the tabulator. The point is that within one block of code, the indentation has to be the same. So if you are working on some project with someone else, you have to agree on indentation for the program to be able to run properly. Most of the people from the Python community agree on 4 spaces (or one tab).

Other conditional statements

Sometimes the else statement is not necessary. The following program does nothing extra if the number is not equal to zero.

number = int(input('Enter a number, to which I will add 3: '))
if number == 0:
    print('This is easy!')
print(number, '+ 3 =', number + 3)

Sometimes several conditions are needed. For this situation, we have the elif statement (combination of else and if). It's between if and else. You can repeat the elif keyword after the first if, but only one branch will be executed, to be precise: the first true one where the conditions are met.

age = int(input('How old are you? '))
if age >= 150:
    print('And from which planet are you?')
elif age >= 18:
    # This branch will not be executed for "200", for example.
    print('We can offer: wine, cider, or vodka.')
elif age >= 1:
    print('We can offer: milk, tea, or water')
elif age >= 0:
    print('Unfortunately, we are out of Sunar.')
else :
    # If no condition is met from above, the age had to be negative.
    print('Visitors from the future are not welcomed here!')

Rock paper scissors

Ifs can be nested - after an if and its indentation, there can be other if.

pc_choise = 'rock'
user_choise = input('rock, paper, or scissors?')

if user_choise == 'rock':
    if pc_choise == 'rock':
        print('Draw.')
    elif pc_choise == 'scissors':
        print ('You win!')
    elif pc_choise == 'paper':
        print ('Computer won!')
elif user_choise == 'scissors':
    if pc_choise == 'rock':
        print('Computer won!')
    elif pc_choise == 'scissors':
        print('Draw.')
    elif pc_choise == 'paper':
        print('You win!')
elif user_choise == 'paper':
    if pc_choise == 'rock':
        print('You win!')
    elif pc_choise == 'scissors':
        print('Computer won!')
    elif pc_choise == 'paper':
        print('Draw.')
else:
    print('I do not understand.')

Yay, your first game!
Now we need to overwrite the pc_choice so it will act randomly. We will talk about how to do this next time.

{
  "data": {
    "sessionMaterial": {
      "id": "session-material:2018/pyladies-en-prague:loops:0",
      "title": "Comparison",
      "html": "\n          \n    \n\n    <h1>Comparisons</h1>\n<p>Do you still remember what an <em>operator</em> is?</p>\n<p>In our homework, we learned some basic arithmetic operators.\nWhen we add one more (<code>//</code>), our list will look like this:</p>\n<table class=\"table\">\n    <tbody><tr>\n        <th>Symbol</th>\n        <th>Example</th>\n        <th>Description</th>\n    </tr>\n    <tr>\n        <td><code>+</code>, <code>-</code>, <code>*</code>, <code>/</code></td>\n        <td><code>1 + 1</code></td>\n        <td>Basic arithmetic</td>\n    </tr>\n    <tr>\n        <td><code>-</code></td>\n        <td><code>-5</code></td>\n        <td>Negation</td>\n    </tr>\n    <tr>\n        <td><code>//</code>; <code>%</code></td>\n        <td><code>7 // 2</code>; <code>7 % 2</code></td>\n        <td>Integer division, remainder</td>\n    </tr>\n    <tr>\n        <td><code>**</code></td>\n        <td><code>3 ** 2</code></td>\n        <td>Power (3 to the power of 2)</td>\n    </tr>\n</tbody></table><p>Python also has other types of operators. <em>Comparison</em> (relational) \noperators are used to compare values.\nTry out what they do!\n(You can try them by using <code>print()</code> in your code,\nor you can try <code>python</code>&apos;s command line.)</p>\n<table class=\"table\">\n    <tbody><tr>\n        <th>Symbol</th>\n        <th>Example</th>\n        <th>Description</th>\n    </tr>\n    <tr>\n        <td><code>==</code>, <code>!=</code></td>\n        <td><code>1 == 1</code>, <code>1 != 1</code></td>\n        <td>equal, not equal</td>\n    </tr>\n    <tr>\n        <td><code>&lt;</code>, <code>&gt;</code></td>\n        <td><code>3 &lt; 5</code>, <code>3 &gt; 5</code></td>\n        <td>greater than, less than</td>\n    </tr>\n    <tr>\n        <td><code>&lt;=</code>, <code>&gt;=</code></td>\n        <td><code>3 &lt;= 5</code>, <code>3 &gt;= 5</code></td>\n        <td>Greater or equal, less or equal</td>\n    </tr>\n</tbody></table><p>Comparison values are called <em>boolean</em> values\n(after <a href=\"http://en.wikipedia.org/wiki/George_Boole\">G. Boole</a>).\nThey are used every time we want to know if something is <code>True</code> or <code>False</code>.\nBoolean types are exactly those two - <code>True</code> and <code>False</code>.</p>\n<p>Like all values, <code>True</code> and <code>False</code> can be assigned to variables:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">true</span> <span class=\"o\">=</span> <span class=\"mi\">1</span> <span class=\"o\">&lt;</span> <span class=\"mi\">3</span>  <span class=\"c1\"># we have to type it in lowercase now, because True is a reserved word in Python</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">true</span><span class=\"p\">)</span>\n\n<span class=\"n\">false</span> <span class=\"o\">=</span> <span class=\"mi\">1</span> <span class=\"o\">==</span> <span class=\"mi\">3</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">false</span><span class=\"p\">)</span>\n</pre></div><div class=\"admonition note\"><p>Note that to test equality, you have to use two equal signs: <code>3 == 3</code>.\nOne equal sign assigns a value to a variable, and two equal signs\ncompare two values (of variables).</p>\n</div><p><code>True</code> and <code>False</code> \ncan be used directly in a program.\nJust keep an eye on capitalisation.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"bp\">True</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"bp\">False</span><span class=\"p\">)</span>\n</pre></div><h2>Conditions</h2>\n<p>Write the following into a new file (e.g. <code>if.py</code>):</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">side</span> <span class=\"o\">=</span> <span class=\"nb\">float</span><span class=\"p\">(</span><span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter the side of a square in centimeters: &apos;</span><span class=\"p\">))</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The perimeter of a square with a side of&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm is &quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span> <span class=\"o\">*</span> <span class=\"mi\">4</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm.&quot;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The area of a square with a side of&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm is&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span> <span class=\"o\">*</span> <span class=\"n\">side</span><span class=\"p\">,</span> <span class=\"s2\">&quot;cm2.&quot;</span><span class=\"p\">)</span>\n</pre></div><p>What happens when you enter a negative number? Does the output make sense?</p>\n<p>As we can see, the computer does exactly what it is told and doesn&apos;t\nthink about context. You have to do that for it.\nIt would be nice if the program could tell the user who enters\na negative number that they entered nonsense.\nHow do we do that?</p>\n<p>Let&#x2019;s try to set a variable that will be <code>True</code> when a user enters a positive number.</p>\n<div class=\"solution\" id=\"solution-0\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/comparisons/index/solutions/0/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <p>You can set the variable like this:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">side</span> <span class=\"o\">=</span> <span class=\"nb\">float</span><span class=\"p\">(</span><span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter the side of a square in centimeters: &apos;</span><span class=\"p\">))</span>\n<span class=\"n\">positive_number</span> <span class=\"o\">=</span> <span class=\"n\">side</span> <span class=\"o\">&gt;</span> <span class=\"mi\">0</span>\n</pre></div>\n    </div>\n</div><p>And then we will tell the program to use this variable. \nFor that purpose we will use the <code>if</code> and <code>else</code> statements.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">side</span> <span class=\"o\">=</span> <span class=\"nb\">float</span><span class=\"p\">(</span><span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter the side of a square in centimeters: &apos;</span><span class=\"p\">))</span>\n<span class=\"n\">positive_number</span> <span class=\"o\">=</span> <span class=\"n\">side</span> <span class=\"o\">&gt;</span> <span class=\"mi\">0</span>\n\n\n<span class=\"k\">if</span> <span class=\"n\">positive_number</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The perimeter of a square with a side of&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm is&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span> <span class=\"o\">*</span> <span class=\"mi\">4</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm.&quot;</span><span class=\"p\">)</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The area of a square with a side of&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span><span class=\"p\">,</span><span class=\"s2\">&quot;cm is&quot;</span><span class=\"p\">,</span> <span class=\"n\">side</span> <span class=\"o\">*</span> <span class=\"n\">side</span><span class=\"p\">,</span> <span class=\"s2\">&quot;cm2.&quot;</span><span class=\"p\">)</span>\n<span class=\"k\">else</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;The side must be a positive number!&quot;</span><span class=\"p\">)</span>\n\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;Thank you for using the geometric calculator.&quot;</span><span class=\"p\">)</span>\n</pre></div><p>So after <code>if</code>, there is a <em>condition</em> which is the\nexpression we&apos;ll use for the decision making.\nAfter the condition you must write a colon (<code>:</code>).\nThe colon is followed by the commands to be executed, if the condition is True.\nIndent the lines 4 spaces after every colon you use in Python.</p>\n<p>Then on the same level as <code>if</code>, write <code>else:</code> followed by a colon. The next lines\ncontain the commands that are executed if the condition is False, and they must also be indented.<br>\nThen you can write other code, not indented, that will be executed every time, because\nthe if statement has already ended.</p>\n<div class=\"admonition note\"><p>The indentation doesn&apos;t need to be 4 spaces, you could use \n2 or even 11, or you can use the tabulator. The point is that\nwithin one block of code, the indentation has to be the same.\nSo if you are working on some project with someone else, you\nhave to agree on indentation for the program \nto be able to run properly. Most of the people\nfrom the Python community agree on 4 spaces (or one tab).</p>\n</div><h2>Other conditional statements</h2>\n<p>Sometimes the <code>else</code> statement is not necessary.\nThe following program does nothing extra if the number is not equal to zero.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">number</span> <span class=\"o\">=</span> <span class=\"nb\">int</span><span class=\"p\">(</span><span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter a number, to which I will add 3: &apos;</span><span class=\"p\">))</span>\n<span class=\"k\">if</span> <span class=\"n\">number</span> <span class=\"o\">==</span> <span class=\"mi\">0</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;This is easy!&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">number</span><span class=\"p\">,</span> <span class=\"s1\">&apos;+ 3 =&apos;</span><span class=\"p\">,</span> <span class=\"n\">number</span> <span class=\"o\">+</span> <span class=\"mi\">3</span><span class=\"p\">)</span>\n</pre></div><p>Sometimes several conditions are needed. For this situation, we have the <code>elif</code> statement\n(combination of <code>else</code> and <code>if</code>). It&apos;s between <code>if</code> and <code>else</code>.\nYou can repeat the <code>elif</code> keyword after the first <code>if</code>, but \nonly one branch will be executed, to be precise: the first true one\nwhere the conditions are met.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">age</span> <span class=\"o\">=</span> <span class=\"nb\">int</span><span class=\"p\">(</span><span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;How old are you? &apos;</span><span class=\"p\">))</span>\n<span class=\"k\">if</span> <span class=\"n\">age</span> <span class=\"o\">&gt;=</span> <span class=\"mi\">150</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;And from which planet are you?&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">elif</span> <span class=\"n\">age</span> <span class=\"o\">&gt;=</span> <span class=\"mi\">18</span><span class=\"p\">:</span>\n    <span class=\"c1\"># This branch will not be executed for &quot;200&quot;, for example.</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;We can offer: wine, cider, or vodka.&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">elif</span> <span class=\"n\">age</span> <span class=\"o\">&gt;=</span> <span class=\"mi\">1</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;We can offer: milk, tea, or water&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">elif</span> <span class=\"n\">age</span> <span class=\"o\">&gt;=</span> <span class=\"mi\">0</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Unfortunately, we are out of Sunar.&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">else</span> <span class=\"p\">:</span>\n    <span class=\"c1\"># If no condition is met from above, the age had to be negative.</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Visitors from the future are not welcomed here!&apos;</span><span class=\"p\">)</span>\n</pre></div><h2>Rock paper scissors</h2>\n<p><code>If</code>s can be nested - after an <code>if</code> and its indentation, there can be other <code>if</code>.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">pc_choise</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;rock&apos;</span>\n<span class=\"n\">user_choise</span> <span class=\"o\">=</span> <span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;rock, paper, or scissors?&apos;</span><span class=\"p\">)</span>\n\n<span class=\"k\">if</span> <span class=\"n\">user_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;rock&apos;</span><span class=\"p\">:</span>\n    <span class=\"k\">if</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;rock&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Draw.&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;scissors&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span> <span class=\"p\">(</span><span class=\"s1\">&apos;You win!&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;paper&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span> <span class=\"p\">(</span><span class=\"s1\">&apos;Computer won!&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">elif</span> <span class=\"n\">user_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;scissors&apos;</span><span class=\"p\">:</span>\n    <span class=\"k\">if</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;rock&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Computer won!&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;scissors&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Draw.&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;paper&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;You win!&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">elif</span> <span class=\"n\">user_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;paper&apos;</span><span class=\"p\">:</span>\n    <span class=\"k\">if</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;rock&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;You win!&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;scissors&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Computer won!&apos;</span><span class=\"p\">)</span>\n    <span class=\"k\">elif</span> <span class=\"n\">pc_choise</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;paper&apos;</span><span class=\"p\">:</span>\n        <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Draw.&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">else</span><span class=\"p\">:</span>\n    <span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;I do not understand.&apos;</span><span class=\"p\">)</span>\n</pre></div><p>Yay, your first game!<br>\nNow we need to overwrite the pc_choice so it will act\nrandomly. We will talk about how to do this next time.</p>\n\n\n        "
    }
  }
}