{"id":552,"date":"2010-10-12T09:26:40","date_gmt":"2010-10-12T09:26:40","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/"},"modified":"2010-10-12T09:26:40","modified_gmt":"2010-10-12T09:26:40","slug":"6-if","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/6-if\/","title":{"rendered":"6: If"},"content":{"rendered":"<!-- Please retain this notice and add more notes if you create a new version.<br \/>\nOriginal lesson author: David Pritchard, daveagp@gmail.com, http:\/\/cscircles.ca<br \/>\nLicense: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/-->\n<p>Up to now, all of our programs have executed their instructions in order without skipping any lines. Here's an example; step back and forth through the code with the buttons or your keyboard's arrow keys.<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=birthYear+%3D+1982%0AcurrentYear+%3D+2013%0Aage+%3D+currentYear+-+birthYear%0Aprint%28%27You+are%27%2C+age%2C+%27years+old%27%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=400&rightStdout=1'><\/iframe><\/p>\n<p>The new ability in this lesson is the\u00a0<strong>if statement<\/strong>, which allows us to perform actions only when certain conditions are met, and skip lines otherwise. For example, let's change our program to output an extra message when someone's age is large enough. We will add two lines: <code>if age &gt; 65:<\/code>\u00a0(meaning, \"if <code>age<\/code> is greater than 65\") and <code>\u00a0 print('Enjoy retirement!')<\/code>.\u00a0Now step through the code again:<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=birthYear+%3D+1982%0AcurrentYear+%3D+2013%0Aage+%3D+currentYear+-+birthYear%0Aif+age+%3E+65%3A%0A+++print%28%27Enjoy+retirement%21%27%29%0Aprint%28%27You+are%27%2C+age%2C+%27years+old%27%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=400&rightStdout=1'><\/iframe><\/p>\n<p>Notice that the new print statement was <strong>skipped<\/strong> because <code>age<\/code> was only 31! What happens with the <strong>exact same program<\/strong> when <code>birthYear<\/code> is changed to 1928?<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=birthYear+%3D+1928%0AcurrentYear+%3D+2013%0Aage+%3D+currentYear+-+birthYear%0Aif+age+%3E+65%3A%0A+++print%28%27Enjoy+retirement%21%27%29%0Aprint%28%27You+are%27%2C+age%2C+%27years+old%27%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=400&rightStdout=1'><\/iframe><\/p>\n<p>Do you notice the difference? The bottom version (with <code>age<\/code> <code><\/code>85) printed out two lines and did not skip any. This is exactly the purpose of the\u00a0<strong>if statement<\/strong>: to check something (is <code>age<\/code> greater than 65?) and to perform certain actions (printing <code>Enjoy retirement!<\/code>) only when the check holds true.<\/p>\n<p>We call the thing being checked the\u00a0<strong>condition<\/strong>, and the statements that are dependent on whether the condition holds true the\u00a0<strong>body<\/strong>. The body has to be <strong>indented<\/strong>\u00a0which means there are extra spaces at the start of the line (like in the example above).\u00a0The body can actually contain more than one statement: to do this, write several\u00a0indented lines. Here's an example.<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=birthYear+%3D+1928%0AcurrentYear+%3D+2013%0Aage+%3D+currentYear+-+birthYear%0Aif+age+%3E+65%3A%0A++++print%28%27Enjoy+retirement%21%27%29%0A++++print%28%27You+turn+100+in%27%2C+100%2BbirthYear%29%0Aprint%28%27You+are%27%2C+age%2C+%27years+old%27%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=480&rightStdout=1'><\/iframe><\/p>\n<ul>\n<li>Try running this code in the <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=birthYear%20%3D%201928%0AcurrentYear%20%3D%202013%0Aage%20%3D%20currentYear%20-%20birthYear%0Aif%20age%20%3E%2065%3A%0A%20%20%20%20print%28%27Enjoy%20retirement%21%27%29%0A%20%20%20%20print%28%27You%20turn%20100%20in%27%2C%20100%2BbirthYear%29%0Aprint%28%27You%20are%27%2C%20age%2C%20%27years%20old%27%29%0A\" target=\"_blank\">console<\/a> or visualizer with birth year 1982. Both of the indented lines are skipped.<\/li>\n<\/ul>\n<p>In the next exercise, we ask you to write a short program with boolean comparisons. We already saw in the examples above that \"<code>if x &gt; y:<\/code>\" means \"if <code>x<\/code> is greater than <code>y<\/code>\". You might also find the following operations useful:<\/p>\n<ul>\n<li><code>if x &lt; y:<\/code> means \"if x is less than y\"<\/li>\n<li><code>if x &gt;= y:<\/code> means \"if x is greater than or equal to y\"<\/li>\n<li><code>if x &lt;= y:<\/code> means \"if x is less than or equal to y\"<\/li>\n<\/ul>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform0\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox0'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>IHOPython<\/span><\/div>Write a program which reads an integer from input using <code>pancakes = int(input())<\/code>. If <code>pancakes<\/code> is more than 3, print out <code>Yum!<\/code> and if <code>pancakes<\/code> is not more than 3, print out <code>Still hungry!<\/code> instead. <a class=\"hintlink\"  id=\"hintlink1\">Hint<\/a><div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory0' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput0\">You may enter input for the program in the box below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit0' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch0\" value=\"Input Switch\" onclick=\"pbInputSwitch(0,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(0)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(0,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect0' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(0,'6.ihop')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(0);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse0\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"0\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"636be973a0d9957d41870ef84743b960\"\/>\n<div id='pbresults0' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>pbInputSwitch(0,\"N\");<\/script>\n<\/p>\n<h2>Structure of an If Statement<\/h2>\n<ul>\n<li>The first line,\n<pre>if \u00abcondition\u00bb:<\/pre>has three parts: the word <code>if<\/code>, the\u00a0<code>\u00ab<span style=\"line-height: 22px\">condition<\/span>\u00bb<\/code> which must be a True\/False expression (more on this below), and a colon <code>:<\/code><\/li>\n<li>Then, the body consisting\u00a0of one or more indented lines. The number of spaces (the amount of indentation) doesn't matter, but being inconsistent will <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=birthYear%20%3D%201928%0AcurrentYear%20%3D%202013%0Aage%20%3D%20currentYear%20-%20birthYear%0Aif%20age%20%3E%2065%3A%0A%20%20print%28%27Enjoy%20retirement%21%27%29%0A%20%20%20%20print%28%27You%20turn%20100%20in%27%2C%20100%2BbirthYear%29%0Aprint%28%27You%20are%27%2C%20age%2C%20%27years%20old%27%29%0A\" target=\"_blank\">cause an error<\/a> since\u00a0Python uses the amount of indentation to determine where you mean the body to start or stop.<\/li>\n<\/ul>\n<p>The body of an if statement is an example of a programming \"block\". Blocks will be used in many other places later on, including \"for loops\" and defining your own functions. (Certain\u00a0other\u00a0programming languages indicate\u00a0blocks is with curly braces <code><code>{}<\/code><\/code>.)<\/p>\n<p>The next exercise is actually 4 exercises in one. You will arrange the lines of a program to get several different results.\u00a0<em>Click on the horizontal bars to open each part; you can do them in any order. As usual, in each part, drag and drop the lines of code to rearrange them.<\/em><\/p>\n<div class=\"accordion\"><br \/>\n<div class='collapseContain hiding'>\n<div class='collapseHead'><span class='icon'><\/span>\nPart 1: Unexpected indent\n<\/div>\n<div class='collapseBody'><form class=\"pbform\" action=\"#\" id=\"pbform2\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox2'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Scramble Exercise: <\/span><span class='title'>Unexpected Indent<\/span><\/div>You must cause the following error: <\/p>\n<pre>IndentationError: unexpected indent<\/pre> <ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble2\">\n <li class=\"pyscramble\">if 1000 &lt; 10:<\/li>\n <li class=\"pyscramble\">   print(&quot;message 1&quot;)<\/li>\n <li class=\"pyscramble\">  print(&quot;message 2&quot;)<\/li>\n <li class=\"pyscramble\">if 2 &gt; 1:<\/li>\n <li class=\"pyscramble\">  print(&quot;message 3&quot;)<\/li>\n<\/ul>\n<input type='hidden' id='usercode2' name='usercode2'\/>\n<div id='pbhistory2' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit2' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse2\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"2\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"4d106e0d6f7081e935072ece2baa5751\"\/>\n<div id='pbresults2' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit2\").value = \"Run program\";document.getElementById(\"inputInUse2\").value = \"N\";<\/script>\n<\/div><\/div><div class='collapseContain hiding'>\n<div class='collapseHead'><span class='icon'><\/span>\nPart 2: Unexpected unindent\n<\/div>\n<div class='collapseBody'><form class=\"pbform\" action=\"#\" id=\"pbform3\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox3'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Scramble Exercise: <\/span><span class='title'>Unexpected Unindent<\/span><\/div>You must cause the following error: <\/p>\n<pre>IndentationError: unindent does not match any outer indentation level<\/pre> <ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble3\">\n <li class=\"pyscramble\">if 1000 &lt; 10:<\/li>\n <li class=\"pyscramble\">  print(&quot;message 2&quot;)<\/li>\n <li class=\"pyscramble\">if 2 &gt; 1:<\/li>\n <li class=\"pyscramble\">  print(&quot;message 3&quot;)<\/li>\n <li class=\"pyscramble\">   print(&quot;message 1&quot;)<\/li>\n<\/ul>\n<input type='hidden' id='usercode3' name='usercode3'\/>\n<div id='pbhistory3' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit3' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse3\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"3\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"71f71bbd18b21a2c29f5a939de4e4526\"\/>\n<div id='pbresults3' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit3\").value = \"Run program\";document.getElementById(\"inputInUse3\").value = \"N\";<\/script>\n<\/div><\/div><div class='collapseContain hiding'>\n<div class='collapseHead'><span class='icon'><\/span>\nPart 3: Indent expected but not found\n<\/div>\n<div class='collapseBody'><form class=\"pbform\" action=\"#\" id=\"pbform4\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox4'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Scramble Exercise: <\/span><span class='title'>Expected Indent<\/span><\/div>You must cause the following error: <\/p>\n<pre>IndentationError: expected an indented block after 'if' statement on line 1<\/pre> <ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble4\">\n <li class=\"pyscramble\">if 1000 &lt; 10:<\/li>\n <li class=\"pyscramble\">   print(&quot;message 1&quot;)<\/li>\n <li class=\"pyscramble\">  print(&quot;message 2&quot;)<\/li>\n <li class=\"pyscramble\">if 2 &gt; 1:<\/li>\n <li class=\"pyscramble\">  print(&quot;message 3&quot;)<\/li>\n<\/ul>\n<input type='hidden' id='usercode4' name='usercode4'\/>\n<div id='pbhistory4' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit4' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse4\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"4\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"1cd75c622a747c15bd3287d83973aaf7\"\/>\n<div id='pbresults4' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit4\").value = \"Run program\";document.getElementById(\"inputInUse4\").value = \"N\";<\/script>\n<\/div><\/div><div class='collapseContain hiding'>\n<div class='collapseHead'><span class='icon'><\/span>\nPart 4: Proper indentation\n<\/div>\n<div class='collapseBody'><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox5'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Scramble Exercise: <\/span><span class='title'>Proper Indentation<\/span><\/div>Don't cause any errors!<ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble5\">\n <li class=\"pyscramble\">if 1000 &lt; 10:<\/li>\n <li class=\"pyscramble\">   print(&quot;message 1&quot;)<\/li>\n <li class=\"pyscramble\">  print(&quot;message 2&quot;)<\/li>\n <li class=\"pyscramble\">if 2 &gt; 1:<\/li>\n <li class=\"pyscramble\">  print(&quot;message 3&quot;)<\/li>\n<\/ul>\n<input type='hidden' id='usercode5' name='usercode5'\/>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse5\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"5\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"b4db381a05ab72c6e8608ea2171eaad7\"\/>\n<div id='pbresults5' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit5\").value = \"Run program\";document.getElementById(\"inputInUse5\").value = \"N\";<\/script>\n<\/div><\/div><\/div>\n<h3>True, False, and <code>bool<\/code><\/h3>\n<p>So far, in the <code>\u00abcondition\u00bb<\/code> part of an <code>if<\/code> statement, we saw a simple numerical comparison <code>x &gt; y<\/code>,\u00a0which is true when <code>x<\/code> is greater than <code>y<\/code> and false when <code>x<\/code> is less than or equal to <code>y<\/code>. More generally, any true\/false value is called <strong>Boolean<\/strong> (see\u00a0<a href=\"http:\/\/en.wikipedia.org\/wiki\/George_Boole\">George Boole<\/a>). In Python, the <code>bool<\/code> type is used to represent Boolean values; only two <code>bool<\/code> values exist, <code>True<\/code> and <code>False<\/code>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform6\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox6'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Boolean expressions<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 110px;'><textarea wrap='off' name='usercode6' id='usercode6'  cols=10 rows=4 readonly='readonly'  style = 'height : 110px;'  class='pyboxCode RO'>\nprint(2&gt;1)\nb = False\nprint(b)\nprint(type(b), type(2&gt;1), type(True))<\/textarea><\/div>\n<div id='pbhistory6' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit6' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(6)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(6,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse6\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"6\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"b696c04c9860d8276e0ff89ec3161af2\"\/>\n<div id='pbresults6' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit6\").value = \"Run program\";document.getElementById(\"inputInUse6\").value = \"N\";<\/script>\n<\/p>\n<p>Note that in Python, when you use the <code>bool<\/code> values <code>True<\/code> and <code>False<\/code> directly in a program, they <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=print%28true%29\" target=\"_blank\">must be capitalized or you will get an error<\/a>.<\/p>\n<h3>Boolean comparisons<\/h3>\n<p>The operators <code>&gt;<\/code>, <code>&lt;<\/code>, <code>&lt;=<\/code>, and <code>&gt;=<\/code> compare two numbers and give back a bool. There are two other ways to compare numbers:<\/p>\n<ul>\n<li><code>x == y<\/code> is the <strong>equality operator<\/strong>, it returns <code>True<\/code> if <code>x<\/code> and <code>y<\/code> are equal<\/li>\n<li><code>x != y<\/code> is the <strong>not-equal operator<\/strong>, it returns <code>True<\/code> if <code>x<\/code> and <code>y<\/code> are not equal<\/li>\n<li><code>==<\/code> and <code>!=<\/code> also work for strings and other types of data<\/li>\n<\/ul>\n<p>(There are two equal signs <code>==<\/code> here since the single equals sign already has the meaning in <code>x = \u00abexpression\u00bb<\/code> of \"assign the variable <code>x<\/code> the value of \u00abexpression\u00bb. Confusing <code>=<\/code> with <code>==<\/code> is a common <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=x%20%3D%201%2B1%0Aif%20x%20%3D%202%3A%20%23should%20be%20%3D%3D%0A%20print%28%22Monkey%22%29\" target=\"_blank\">source<\/a> of <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=n%20%3D%2010%0As%20%3D%3D%20n%2An%20%23should%20be%20%3D\" target=\"_blank\">bugs<\/a>.)<\/p>\n<p>Here is an exercise that will involve one of the new comparisons.<br \/>\n<form class=\"pbform\" action=\"#\" id=\"pbform7\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox7'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>What's Your Sign?<\/span><\/div>Write a program that reads an integer from input, then outputs one of the capitalized words <code>Positive<\/code>, <code>Negative<\/code>, or <code>Zero<\/code> according to whether the number is positive, negative, or zero.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode7' id='usercode7'  cols=10 rows=20   class='pyboxCode RW'>\nx=int(input())\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory7' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput7\">You may enter input for the program in the box below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<input type='hidden' id='defaultCode7' value='x=int(input())\\n'><\/input>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit7' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch7\" value=\"Input Switch\" onclick=\"pbInputSwitch(7,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(7)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(7,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect7' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(7,'6.sign')\" >History<\/option>\n<option name='default' data-pbonclick=\"pbSetText(7,descape($('#defaultCode7').val()))\" >Reset code to default<\/option>\n<option name='help' data-pbonclick=\"helpClick(7);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse7\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"7\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"66131dbd30d3f5d03ae923430cb6b01f\"\/>\n<div id='pbresults7' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>pbInputSwitch(7,\"N\");<\/script>\n<\/p>\n<p>We just introduced the concept of a <strong>block<\/strong> (several lines grouped together at the same indentation level). You can have a block inside another block:<\/p>\n<pre>if password=='openSesame':\n \u00a0print('User logged on.')\n \u00a0if hour&gt;17:\n \u00a0 \u00a0print('Good evening!')\n \u00a0print('Enter a command:')<\/pre>Here the outer block consists of 4 lines and the inner block consists of just 1 line:\u00a0<pre>\nif password=='openSesame':  <div style=\"margin:0px 20px; margin:0ch 1.9ch; background: #CCF; border: solid blue 1px; border: solid blue 0.1ch;\">print('User logged on.')<br\/>if hour&gt;17:\n<div style=\"margin:0px 20px; margin: 0ch 1.9ch; background: #FCC; border: solid red 1px; border: solid red 0.1ch;\">print('Good evening!')<\/div>print('Enter a command:')<\/div><\/pre><\/p>\n<p><div class='pybox modeNeutral' id='pybox8'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Multiple Choice Exercise: <\/span><span class='title'>Nested <code>if<\/code>s<\/span><\/div><div>Which of the following outputs is <strong>not<\/strong> possible for this program?<\/div><label>Your choice: <\/label><select id=\"pyselect8\"><option value=\"d\" selected>Select one<\/option><option value=\"r\">one line: 'User logged on.'<\/option><option value=\"w\">no output<\/option><option value=\"w\">two lines: 'User logged on.' and 'Enter a command:'<\/option><option value=\"w\">three lines: 'User logged on.', 'Good evening!', and 'Enter a command:'<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"6.nested\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(8)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults8\"><\/div><div class=\"epilogue\">Correct! If any messages are shown, it must be the case that the outer (blue) block was executed, or in other words the password was correct. In this case, even if <code>hour&gt;17<\/code> is false (and the inner block is skipped), the line <code>print('Enter a command:')<\/code> of the outer block will still be executed.<\/div><\/div>\n<p>Now, you must use nested blocks to write a slightly more complex age calculator.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform9\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox9'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Age checker<\/span><\/div>Write a program that reads an integer from input, representing someone's age. If the age is 18 or larger, print out <code>You can vote<\/code>. If the age is between 0 and 17 inclusive, print out <code>Too young to vote<\/code>. If the age is less than 0, print out <code>You are a time traveller<\/code>.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode9' id='usercode9'  cols=10 rows=20   class='pyboxCode RW'>\nage = int(input())\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory9' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput9\">You may enter input for the program in the box below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<input type='hidden' id='defaultCode9' value='age = int(input())\\n'><\/input>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit9' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch9\" value=\"Input Switch\" onclick=\"pbInputSwitch(9,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(9)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(9,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect9' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(9,'6.agecheck')\" >History<\/option>\n<option name='default' data-pbonclick=\"pbSetText(9,descape($('#defaultCode9').val()))\" >Reset code to default<\/option>\n<option name='help' data-pbonclick=\"helpClick(9);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse9\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"9\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"477e8c0c24d19f1651d5457006245965\"\/>\n<div id='pbresults9' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>pbInputSwitch(9,\"N\");<\/script>\n<\/p>\n<p>Later, in lesson 9, we will see that situations involving multiple boolean checks can be simplified using the <code>else<\/code> and <code>elif<\/code> (else if) commands as well as the Boolean operators \"and\", \"or\", and \"not\". For now, you are ready to proceed to the next lesson.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Up to now, all of our programs have executed their instructions in order without skipping any lines. Here's an example; step back and forth through the code with the buttons or your keyboard's arrow keys. The new ability in this &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/6-if\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-552","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/552"}],"collection":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/comments?post=552"}],"version-history":[{"count":0,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/552\/revisions"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}