{"id":997,"date":"2010-11-23T21:17:02","date_gmt":"2010-11-23T21:17:02","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/"},"modified":"2010-11-23T21:17:02","modified_gmt":"2010-11-23T21:17:02","slug":"9-else-and-or-not","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/9-else-and-or-not\/","title":{"rendered":"9: Else, And, Or, Not"},"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>This lesson will allow you to do complex case-checking more elegantly, using two new parts of the Python language.<\/p>\n<ul>\n<li>after an <code>if \u00abC\u00bb<\/code> statement, an <code>else<\/code> statement executes only if <code>C<\/code> is <em>false<\/em><\/li>\n<li>you can combine boolean conditions using <code>A and B<\/code>, <code>A or B<\/code>, and\u00a0<code>not A<\/code><\/li>\n<\/ul>\n<h1><code>else<\/code><\/h1>\n<p>A common task in writing programs is that you want to test some condition, and take either one action or another action, depending on the condition is true or false. <a href=\"\/6-if\/\">Earlier<\/a>, an exercise asked you to do something if <code>age<\/code> was less than 0, and something else if <code>age<\/code> is not less than 0; the code was something like<\/p>\n<pre>if age &gt;= 0: \u00a0\n  print('You are not necessarily a time traveller')\nif age &lt; 0:\n \u00a0print('You are a time traveller')<\/pre>Now let's rewrite it to use <code>else<\/code>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform0\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox0'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>\u00a0<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\nage = int(input())\nif age &gt;= 0:\n  print('You are not necessarily a time traveller')\nelse:    # instead of a second 'if'!\n  print('You are a time traveller')<\/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><\/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=\"4fff70335a8bea800b809414452d8a8c\"\/>\n<div id='pbresults0' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>pbInputSwitch(0,\"N\");<\/script>\n<\/p>\n<p>More generally, you use <code>else<\/code> via the following pair of block statements:<\/p>\n<pre>if \u00abtest\u00bb:\n   \u00abtrue-body\u00bb        # an indented block\nelse:\n   \u00abfalse-body\u00bb       # another indented block<\/pre>Python evaluates the test. If it is true the true-body is executed, and if it is false the false-body is executed.<\/p>\n<h2>The Philosophy of <code>else<\/code><\/h2>\n<p>We don't get new powers from <code>else<\/code>, but it makes code much easier to read, debug, and maintain. Here are two code fragments that do the same thing:<\/p>\n<table id=\"AB\">\n<tbody>\n<tr>\n<td>\n<div>Version A<\/div>\n<pre>if height &lt; 256:\n   print('Too short for this ride')\nelse:\n   print('Welcome aboard!')<\/pre>\n<\/td>\n<td>\n<div>Version B<\/div>\n<pre>if height &lt; 256:\n   print('Too short for this ride')\nif height &gt;= 256:\n   print('Welcome aboard!')<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Both do the same thing, and <strong>B<\/strong> doesn't even need <code>else<\/code>. However, most programmers would agree that <strong>A<\/strong> is better. For example, with <strong>A<\/strong>,\u00a0changing the condition (e.g., using 128 instead of 256) requires only one change to the code instead of two. Also, <strong>A<\/strong> can be immediately understood by a human reader, while in <strong>B<\/strong> you need to check and think whether or not both, or neither conditions can be true.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform1\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox1'>\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'>Absolute Value<\/span><\/div>The <em>absolute value<\/em> of a number is defined as follows. For a number <em>x<\/em>\u00a0that is positive or zero,\u00a0the absolute value of <em>x <\/em>is <em>x<\/em>. Otherwise, when\u00a0<em>x<\/em>\u00a0is a negative number,\u00a0the absolute value of <em>x<\/em>\u00a0is <em>-x<\/em>, or in other words the same as <em>x<\/em>\u00a0but without the minus sign. For example the absolute value of <code>5<\/code> is <code>5<\/code>, and the absolute value of <code>-10<\/code> is <code>10<\/code>.\u00a0Using <code>if<\/code> and <code>else<\/code>, write a program that reads an integer as input, and prints its absolute value.<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='usercode1' id='usercode1'  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='pbhistory1' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput1\">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='defaultCode1' value='x=int(input())\\n'><\/input>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit1' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch1\" value=\"Input Switch\" onclick=\"pbInputSwitch(1,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(1)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(1,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect1' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(1,'9.abs')\" >History<\/option>\n<option name='default' data-pbonclick=\"pbSetText(1,descape($('#defaultCode1').val()))\" >Reset code to default<\/option>\n<option name='help' data-pbonclick=\"helpClick(1);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse1\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"1\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"84b20de867847e2e73797de53cddb156\"\/>\n<div id='pbresults1' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(1);});pbInputSwitch(1,\"N\");<\/script>\n<\/p>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> Python has a built-in function <code>abs(x)<\/code> to compute the absolute value of <code>x<\/code>. The grader above prevents you from using it, but you can use it later. <\/span><\/td><\/table><\/p>\n<h2><code>elif<\/code><\/h2>\n<p>Python introduces one other keyword, <code>elif<\/code>, to make it easier to check several conditions in a row. The most basic form of <code>elif<\/code> is the following:<\/p>\n<pre>if \u00abtest1\u00bb:\n   \u00abbody1\u00bb        # runs if test1 is true\nelif \u00abtest2\u00bb:\n   \u00abbody2\u00bb        # runs if test1 is false and test2 is true<\/pre>As you may have guessed, <code>elif<\/code> is short for \"else if\", since it is the same as putting an if statement inside an else block. But, it leads to shorter code and less indentation, which makes your program easier to read, debug, and edit. What's more, you can combine <em>any number<\/em> of elif statements in a row and even add an optional <code>else<\/code> statement to the end:<\/p>\n<pre>if \u00abtest1\u00bb:\n   \u00abbody1\u00bb      # runs if test1 is true\nelif \u00abtest2\u00bb:\n   \u00abbody2\u00bb      # runs if test1 is false and test2 is true\nelif \u00abtest3\u00bb:\n   \u00abbody3\u00bb      # runs if test1 &amp; test2 both false and test3 is true\nelse:           # these last two lines are optional\n   \u00abelse-body\u00bb  # runs if ALL the tests are false<\/pre>&nbsp;<\/p>\n<p>Here is an example of <code>elif<\/code> used inside of a loop. Can you predict the output before it runs?<\/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=for+x+in+range%281%2C+10%29%3A%0A++if+x+%25+2+%3D%3D+0%3A%0A++++print%28x%2C+%27is+even%27%29%0A++elif+x+%25+3+%3D%3D+0%3A%0A++++print%28x%2C+%27is+an+odd+multiple+of+3%27%29%0A++else%3A%0A++++print%28x%2C+%27not+divisible+by+2+or+3%27%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=450px&rightStdout=1'><\/iframe><\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform2\" method=\"POST\">\n<div class='pybox modeNeutral ' 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'>Coding Exercise: <\/span><span class='title'>First, Second, Third<\/span><\/div>The words 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th are called <em>ordinal adjectives.<\/em> Write a program which reads an integer <em>x<\/em> between 1 and 9 from input. The program should output the ordinal adjective corresponding to <em>x<\/em>. <br\/> <strong>Hint<\/strong>: you don't need to have 9 separate cases; 4 is enough.<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='usercode2' id='usercode2'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory2' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput2\">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='submit2' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch2\" value=\"Input Switch\" onclick=\"pbInputSwitch(2,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(2)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(2,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect2' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(2,'9.ordinal')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(2);\" >Help<\/option>\n<\/select><\/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=\"c4b3f10cc0deac89d5354ed7137f3680\"\/>\n<div id='pbresults2' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(2);});pbInputSwitch(2,\"N\");<\/script>\n<\/p>\n<h2>Boolean Operators: <code>and<\/code>, <code>or<\/code>, <code>not<\/code><\/h2>\n<p>You can combine boolean expressions using \"<code>and<\/code>\", \"<code>or<\/code>\", and \"<code>not<\/code>\", which are the same as in the English language.<\/p>\n<ul>\n<li>The expression <code>A and B<\/code> is true if both <code>A<\/code> is true and <code>B<\/code> is true, and false if either is false. (For example, you get wet if it rains <code>and<\/code> you forgot your umbrella.)<\/li>\n<li>The expression <code>A or B<\/code> is true if either <code>A<\/code> is true or <code>B<\/code> is true, and false if both are false. (For example, school is closed if it is a holiday <code>or<\/code> it is a weekend.)<\/li>\n<li>The expression <code>not A<\/code> is true if <code>A<\/code> is false, and false if <code>A<\/code> is true. (For example, you are hungry if you have <code>not<\/code> eaten lunch.)<\/li>\n<\/ul>\n<p>Here is a program which automatically displays all of the possibilities. Just like the 'multiplication tables' you remember from grade school, this is called a <em>truth table<\/em>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform3\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox3'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Truth tables<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode3' id='usercode3'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\nprint(\"  A      B       not A  not B  A and B  A or B\")\nprint(\"----------------------------------------------\")\nfor A in [False, True]:               # \"for\" loop with list\t\n    for B in [False, True]:           # will be taught in lesson 13\n        print(A, \" \", B, \"   \", not A, \" \", not B, \" \", A and B, \" \", A or B)<\/textarea><\/div>\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<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(3)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(3,'N')\" ><\/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=\"23fac91eb493ba893eb781d9128bd39c\"\/>\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<\/p>\n<p>As an example of using <code>and<\/code>, here is a program which converts numbers to letters, with some error-checking.<br \/>\n<form class=\"pbform\" action=\"#\" id=\"pbform4\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox4'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>An example of <code>and<\/code>: Converting numbers to letters, with 1=A, 2=B, etc.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode4' id='usercode4'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\nx = int(input())\nif x>=1 and x<=26:\n    print('letter', x, 'in the alphabet:', chr(ord('A')+(x-1)))\nelse:\n    print('invalid input:', x)<\/textarea><\/div>\n<div id='pbhistory4' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput4\">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='submit4' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch4\" value=\"Input Switch\" onclick=\"pbInputSwitch(4,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(4)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(4,'N')\" ><\/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=\"4b610da4b77d47e08a914c94baf24596\"\/>\n<div id='pbresults4' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>pbInputSwitch(4,\"N\");<\/script>\n<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral ' 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'>Coding Exercise: <\/span><span class='title'>26 Letters<\/span><\/div>Write a program which does the reverse of the example above: it should take a character as input and output the corresponding number (between 1 and 26). Your program should only accept <em>capital<\/em> letters. As error-checking, print <code>invalid<\/code> if the input is not a capital letter. <a class=\"hintlink\"  id=\"hintlink6\">Hint<\/a><a class=\"hintlink\"  id=\"hintlink7\">Alternate string comparison method<\/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='usercode5' id='usercode5'  cols=10 rows=20   class='pyboxCode RW'>\nletter = input()\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput5\">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='defaultCode5' value='letter = input()\\n'><\/input>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch5\" value=\"Input Switch\" onclick=\"pbInputSwitch(5,'N')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(5)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(5,'N')\" ><\/td>\n<\/tr><\/table><select id='pbSelect5' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(5,'9.numberify')\" >History<\/option>\n<option name='default' data-pbonclick=\"pbSetText(5,descape($('#defaultCode5').val()))\" >Reset code to default<\/option>\n<option name='help' data-pbonclick=\"helpClick(5);\" >Help<\/option>\n<\/select><\/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=\"914bc16d897335d6f081eab91eae9621\"\/>\n<div id='pbresults5' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(5);});pbInputSwitch(5,\"N\");<\/script>\n<\/p>\n<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'>De Morgan's Law<\/span><\/div><div>Which of the following expressions is equivalent to <code>A or B<\/code>?<\/div><label>Your choice: <\/label><select id=\"pyselect8\"><option value=\"d\" selected>Select one<\/option><option value=\"r\">not ((not A) and (not B))<\/option><option value=\"w\">(not A) and (not B)<\/option><option value=\"w\">not (A and B)<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"9.demorgan\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(8)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults8\"><\/div><div class=\"epilogue\">Correct! Here is one way to arrive at this answer. First, <code>not (A or B)<\/code> is only true when both <code>A<\/code> and <code>B<\/code> are false. Also, note that <code>(not A) and (not B)<\/code> is only true if both <code>not A<\/code> and <code>not B<\/code> are true, i.e. if both <code>A<\/code> and <code>B<\/code> are false. So we have the following equality:<pre>(not A) and (not B) = not (A or B)<\/pre>Put a <code>not<\/code> around both sides, so we deduce<pre>not ((not A) and (not B)) = not (not (A or B))<\/pre>and observe that <code>not(not X))<\/code> always equals <code>X<\/code>, so<pre>not ((not A) and (not B)) = not (not (A or B)) = A or B<\/pre>This way of rewriting a boolean expression is one of <a href='http:\/\/en.wikipedia.org\/wiki\/De_Morgan%27s_laws'>De Morgan&#39;s laws<\/a>.<\/div><\/div>\n<h3>Order of Operations<\/h3>\n<p><span style=\"color: #444444;line-height: 24px\">Boolean operators have an \"order of operations\" just like mathematical operators. The order is<\/span><\/p>\n<p style=\"text-align: center\"><strong>NAO<\/strong>: not (highest precedence), and, or (lowest precedence)<\/p>\n<p style=\"text-align: left\">so for example,<\/p>\n<p style=\"text-align: center\"><code>not x or y and z<\/code> <span style=\"padding-right: 40px;padding-left: 40px\">means<\/span> <code>(not x) or (y and z)<\/code><\/p>\n<p>We conclude the lesson with a short question using these facts.<br \/>\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'>Multiple Choice Exercise: <\/span><span class='title'>Order of Operations<\/span><\/div><div>What is the value of <\/p>\n<pre>A or not B and C<\/pre> if (A, B, C) = (False, True, True)? <a class=\"hintlink\"  id=\"hintlink10\">Hint<\/a><\/div><label>Your choice: <\/label><select id=\"pyselect9\"><option value=\"d\" selected>Select one<\/option><option value=\"r\">False<\/option><option value=\"w\">True<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"9.multi\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(9)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults9\"><\/div><div class=\"epilogue\">Correct! The order of operations makes this equivalent to<pre>A or ((not B) and C)<\/pre>substituting the values, we have<pre>False or ((not True) and True)<\/pre>and now simplifying one step at a time gives<pre>False or ((not True) and True)<br\/>= False or (False and True)<br\/>= False or False<br\/>= False<\/pre><\/div><\/div>Once you complete this, you are ready for the next lesson.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This lesson will allow you to do complex case-checking more elegantly, using two new parts of the Python language. after an if \u00abC\u00bb statement, an else statement executes only if C is false you can combine boolean conditions using A &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/9-else-and-or-not\/\">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-997","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/997"}],"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=997"}],"version-history":[{"count":0,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/997\/revisions"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=997"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}