{"id":76,"date":"2018-07-23T16:14:44","date_gmt":"2018-07-23T16:14:44","guid":{"rendered":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/chapter\/unit-4-control-structures-making-decisions-and-looping-in-computing-data-and-information-processing-in-python\/"},"modified":"2018-10-05T16:04:34","modified_gmt":"2018-10-05T16:04:34","slug":"unit-4-control-structures-making-decisions-and-looping-in-computing-data-and-information-processing-in-python","status":"publish","type":"chapter","link":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/chapter\/unit-4-control-structures-making-decisions-and-looping-in-computing-data-and-information-processing-in-python\/","title":{"raw":"UNIT 4: Control Structures: Making Decisions and Looping in computing. Data and Information Processing in Python.","rendered":"UNIT 4: Control Structures: Making Decisions and Looping in computing. Data and Information Processing in Python."},"content":{"raw":"<div class=\"unit-4:-control-structures:-making-decisions-and-looping-in-computing.-data-and-information-processing-in-python.\">\r\n<h1><a id=\"_Toc519230974\"><\/a>Learning Objectives<\/h1>\r\n<ul>\r\n \t<li>Read and write programs using the Python IF and IF\/ELIF\/ELSE statements to implement a simple decision structures.<\/li>\r\n \t<li>Write simple exception handling code to catch simple Python run-time errors.<\/li>\r\n \t<li>Read and write programs using the Python FOR and WHILE statements to implement a simple loop structures.<\/li>\r\n \t<li>Construct and implement algorithms that use decision and loop structures.<\/li>\r\n \t<li>Apply basic file processing concepts and techniques for reading and writing text files in Python.<\/li>\r\n<\/ul>\r\n&nbsp;\r\n<ul>\r\n \t<li><a href=\"#_Toc519230975\">Boolean Expressions<\/a><\/li>\r\n \t<li><a href=\"#_Toc519230976\">Logical Operators<\/a><\/li>\r\n \t<li><a href=\"#_Toc519230977\">Conditional Execution<\/a><\/li>\r\n<\/ul>\r\n<\/div>\r\n<div class=\"unit-4:-control-structures:-making-decisions-and-looping-in-computing.-data-and-information-processing-in-python.\">\r\n<h1><a id=\"_Toc519230975\"><\/a>Boolean Expressions<\/h1>\r\n<p class=\"import-Normal\">Arithmetic expressions evaluate to numeric values; a Boolean expression may have only one of two possible values: <strong>false<\/strong> or <strong>true<\/strong>. While on the surface Boolean expressions may appear very limited compared to numeric expressions, they are essential for building more interesting and useful programs.<\/p>\r\nThe simplest Boolean expressions in Python are <code>True<\/code> and <code>False<\/code>. In the Python interactive shell we see:\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; True<\/code>\r\n<code>True<\/code>\r\n<code>&gt;&gt;&gt; False<\/code>\r\n<code>False<\/code>\r\n<code>&gt;&gt;&gt; type(True)<\/code>\r\n<code>&lt;class 'bool'&gt;<\/code>\r\n<code>&gt;&gt;&gt; type(False)<\/code>\r\n<code>&lt;class 'bool'&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">We see that <code>bool<\/code> is the name of the class representing Python\u2019s Boolean expressions. The following code <code>(booleanVars.py)<\/code> is a simple program that shows how Boolean variables can be used.<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code># Assign some Boolean variables<\/code>\r\n<code>a = True<\/code>\r\n<code>b = False<\/code>\r\n<code>print('a =', a, ' b =', b)<\/code>\r\n<code># Reassign a<\/code>\r\n<code>a = False<\/code>\r\n<code>print('a =', a, ' b =', b)<\/code><\/p>\r\n\r\n<\/div>\r\nThe results of running this program are shown below:\r\n<div class=\"textbox\"><code>a = True b = False<\/code>\r\n<code>a = False b = False<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">A Boolean variable is also a Boolean expression as we saw in Unit 2. An expression comparing numeric expressions for equality or inequality is also a Boolean expression. The simplest kinds of Boolean expressions use relational operators (or comparison operators) to compare two expressions. Table 6 lists the relational operators available in Python.<\/p>\r\n\r\n<table>\r\n<tbody>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Expression<\/strong><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Meaning<\/strong><\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x == y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>equals<\/em> y (mathematical equality, not assignment); otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x &lt; y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>less than<\/em> y; otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x &lt;= y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>less than and equal to y<\/em>; otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x &gt; y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>greater than<\/em> y; otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x &gt;= y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>greater than and equal to y<\/em>; otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>x != y<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">True if x <em>not equal to<\/em> y; otherwise, false<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p style=\"text-align: center\"><small><a id=\"_Toc519003537\"><\/a>Table 6: Python Relationa\/Comparisonl Operators<\/small><\/p>\r\n<p class=\"import-Normal\">In the Python interactive shell we see some examples of Boolean expressions:<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; 10 &lt; 20<\/code>\r\n<code>True<\/code>\r\n<code>&gt;&gt;&gt; 10 &gt;= 20<\/code>\r\n<code>False<\/code>\r\n<code>&gt;&gt;&gt; x = 19<\/code>\r\n<code>&gt;&gt;&gt; y = 29<\/code>\r\n<code>&gt;&gt;&gt; x &lt; 100<\/code>\r\n<code>True&gt;&gt;&gt; x != y<\/code>\r\n<code>True<\/code><\/div>\r\n<p class=\"import-Normal\">An expression like <code>10 &lt; 20<\/code> is legal but of little use, since <code>10 &lt; 20<\/code> is always true; the expression <code>True<\/code> is equivalent, simpler, and less likely to confuse human readers. Since variables can change their values during a program\u2019s execution (and often do!), Boolean expressions are most useful when their truth values depend on the values of one or more variables.<\/p>\r\n<p class=\"import-Normal\">The relational\/comparison operators are binary operators and are all left associative. They all have a lower precedence than any of the arithmetic operators; therefore, Python evaluates the expression<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>x + 2 &lt; y \/ 10<\/code><\/p>\r\n<p class=\"import-Normal\">as if parentheses were placed as so:<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>(x + 2) &lt; (y \/ 10)<\/code><\/p>\r\n\r\n<h1><a id=\"_Toc519230976\"><\/a>Logical operators<\/h1>\r\n<p class=\"import-Normal\">There are three logical operators: <code>and<\/code>, <code>or<\/code>, and <code>not<\/code>. The semantics (meaning) of these operators is similar to their meaning in English. For example, <code>x &gt; 0<\/code> and <code>x &lt; 10<\/code> is true only if <code>x<\/code> is greater than 0 and less than 10.<\/p>\r\n<p class=\"import-Normal\"><code>n%2 == 0 or n%3 == 0<\/code> is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.<\/p>\r\n<p class=\"import-Normal\">Finally, the <code>not<\/code> operator negates a Boolean expression, so <code>not (x &gt; y)<\/code> is true if <code>x &gt; y<\/code> is false, that is, if <code>x<\/code> is less than or equal to <code>y<\/code>.<\/p>\r\nStrictly speaking, the operands of the logical operators should be Boolean expressions, but Python is not very strict. Any nonzero number is interpreted as <code>True<\/code>:\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; 42 and True<\/code>\r\n<code>True<\/code><\/div>\r\n<p class=\"import-Normal\">This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).<\/p>\r\n\r\n<h1><a id=\"_Toc519230977\"><\/a>Conditional execution<\/h1>\r\nIn order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the <code style=\"font-weight: bold\">if<\/code> statement:\r\n<div class=\"textbox\"><code>if x &gt; 0:<\/code>\r\n<code style=\"padding-left: 30px\">print('x is positive')<\/code><\/div>\r\n\r\n[caption id=\"\" align=\"alignright\" width=\"242\"]<img src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161431\/image42.png\" alt=\"image\" width=\"242\" height=\"245\" \/> Figure 41: Simple IF Conditional Flowchart[\/caption]\r\n<p class=\"import-Normal\">The Boolean expression after <code>if<\/code> is called the condition. If it is true, the indented statement runs. If not, nothing happens. See the corresponding flowchart in figure 42.<\/p>\r\n<p class=\"import-Normal\"><code>if<\/code> statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.<\/p>\r\n<p class=\"import-Normal\">There is no limit on the number of statements that can appear in the body, but there has to be at least one.<\/p>\r\n\r\n\r\n<hr \/>\r\n<p class=\"import-Normal\">A second form of the if statement is \u201calternative execution\u201d (<code style=\"font-weight: bold\">if-else<\/code>), in which there are two possibilities and the condition determines which one runs. The syntax looks like this:<\/p>\r\n\r\n<div class=\"textbox\" style=\"padding-left: 30px\">\r\n\r\n<code>if x % 2 == 0:<\/code>\r\n<code style=\"padding-left: 30px\">print('x is even')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print('x is odd')<\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n\r\n[caption id=\"\" align=\"alignright\" width=\"527\"]<img class=\"\" style=\"font-size: 1em\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161432\/image43.png\" alt=\"image\" width=\"527\" height=\"286\" \/> Figure 42: Alternative Execution Conditional Flowchart[\/caption]\r\n<p class=\"import-Normal\"><span class=\"import-y0nh1b\">Modulus<\/span><span class=\"import-y0nh1b\"> or remainder <\/span><span class=\"import-y0nh1b\">operator<\/span><span class=\"import-y0nh1b\">, \u2018<\/span><code><span class=\"import-y0nh1b\">%<\/span><\/code><span class=\"import-y0nh1b\">\u2019, returns the remainder of two numbers. So in this example, i<\/span>f the remainder when <code>x<\/code> is divided by 2 is 0, then we know that <code>x<\/code> is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution. See the corresponding flowchart in figure 42.<\/p>\r\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code><span class=\"import-y0nh1b\">if <\/span><\/code><span lang=\"en\" xml:lang=\"en\">statement is used to check a condition: <\/span><em lang=\"en\" xml:lang=\"en\">if<\/em><span lang=\"en\" xml:lang=\"en\"> the condition is true, we run a <\/span><span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> of statements (called the <\/span><em lang=\"en\" xml:lang=\"en\">if-block<\/em><span lang=\"en\" xml:lang=\"en\">), <\/span><em lang=\"en\" xml:lang=\"en\">else<\/em><span lang=\"en\" xml:lang=\"en\"> we process another <\/span><span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> of statements (called the <\/span><em lang=\"en\" xml:lang=\"en\">else-block<\/em><span lang=\"en\" xml:lang=\"en\">). The <\/span><em lang=\"en\" xml:lang=\"en\">else<\/em><span lang=\"en\" xml:lang=\"en\"> clause is optional. In our earlier examples we only had one statement in a block. <\/span>Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional (<code style=\"font-weight: bold\">if-elif-else<\/code>). <span lang=\"en\" xml:lang=\"en\">The following program, <\/span><code>ifElse.py<\/code><span lang=\"en\" xml:lang=\"en\">, show<\/span><span lang=\"en\" xml:lang=\"en\">s<\/span><span lang=\"en\" xml:lang=\"en\"> us multiple statements in each block.<\/span><\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>number = 23<\/code>\r\n<code>guess = int(input('Enter an integer : '))<\/code>\r\n\r\n<code>if guess == number:<\/code>\r\n<code style=\"padding-left: 30px\"># New block starts here<\/code>\r\n<code style=\"padding-left: 30px\">print('Congratulations, you guessed it.')<\/code>\r\n<code style=\"padding-left: 30px\">print('(but you do not win any prizes!)')<\/code>\r\n<code style=\"padding-left: 30px\"># New block ends here<\/code>\r\n<code>elif guess &lt; number:<\/code>\r\n<code style=\"padding-left: 30px\"># Another block<\/code>\r\n<code style=\"padding-left: 30px\">print('No, it is a little higher than that')<\/code>\r\n<code style=\"padding-left: 30px\"># You can do whatever you want in a block ...<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print('No, it is a little lower than that')<\/code>\r\n<code style=\"padding-left: 30px\"># you must have guessed &gt; number to reach here<\/code>\r\n\r\n<code>print('Done')<\/code>\r\n<code># This last statement is always executed,<\/code>\r\n<code># after the if statement is executed.<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">In this program, we take guesses from the user and check if it is the number that we have. We set the variable <code>number<\/code> to any integer we want, say 23. Then, we take the user's guess using the <code>input()<\/code> function. We then convert this string to an integer using <code>int<\/code> and then store it in the variable <code>guess<\/code>.<\/p>\r\n<p class=\"import-Normal\">Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that.<\/p>\r\n<p class=\"import-Normal\">After Python has finished executing the complete <code>if<\/code> statement along with the associated <code>elif<\/code> and <code>else<\/code> clauses, it moves on to the next statement in the block containing the <code>if<\/code> statement. In this case, it is the main block (where execution of the program starts), and the next statement is the <code>print('Done')<\/code> statement. After this, Python sees the end of the program and simply finishes up.<\/p>\r\nThe following code is another example of a conditional statement with more than two branches:\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>if x &lt; y:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is less than y')<\/code>\r\n<code class=\"import-Normal\">elif x &gt; y:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is greater than y')<\/code>\r\n<code class=\"import-Normal\">else:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x and y are equal')<\/code><\/p>\r\n\r\n<\/div>\r\n\r\n[caption id=\"\" align=\"aligncenter\" width=\"615\"]<img class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161434\/image44.png\" alt=\"image\" width=\"615\" height=\"385\" \/> Figure 43: Two or More Branches Conditional Flowchart[\/caption]\r\n<p class=\"import-Normal\"><code>elif<\/code> is an abbreviation of \u201celse if\u201d. Again, exactly one branch will run. There is no limit on the number of <code>elif<\/code> statements. See the corresponding flowchart in figure 43. If there is an <code>else<\/code> clause, it has to be at the end, but there doesn\u2019t have to be one. See the following example:<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>if choice == 'a':<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_a()<\/code>\r\n<code class=\"import-Normal\">elif choice == 'b':<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_b()<\/code>\r\n<code class=\"import-Normal\">elif choice == 'c':<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_c()<\/code><\/p>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first<code> true<\/code> branch runs. It is good practice to include the <code>else<\/code> clause as the final branch in the <code style=\"font-weight: bold\">if-elif-else<\/code> statement.<\/p>\r\n\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230978\"><\/a><span class=\"import-Heading3Char\">Practic<\/span><span class=\"import-Heading3Char\">e <\/span><span class=\"import-Heading3Char\">\u2013<\/span> Write a program to accept a test score as input and print out the corresponding letter grade. First examine the flowchart (figure 44) of the problem we are solving. Then, using the Python editor, enter the following code (save as <code>testGrade.py<\/code> ):<\/h2>\r\n[caption id=\"\" align=\"alignnone\" width=\"552\"]<img src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161436\/image45.png\" alt=\"image\" width=\"552\" height=\"395\" \/> Figure 44: if-elif-else Conditional Flowchart[\/caption]\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>#accept a test score as input and print out the corresponding letter grade<\/code>\r\n<code>testScore = float(input(\"Enter a test score from 0 to 100: \"))<\/code>\r\n<code># conditional statement to determine and print the test letter grade<\/code>\r\n<code>if testScore &gt;= 90:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is A\")<\/code>\r\n<code>elif testScore &gt;= 80:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is B\")<\/code>\r\n<code>elif testScore &gt;= 70:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is C\")<\/code>\r\n<code>elif testScore &gt;= 60:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is D\")<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is F\")<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">Output:<\/p>\r\n<p class=\"import-Normal\"><img class=\"aligncenter\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161438\/image46.png\" alt=\"image\" width=\"488.750971128609px\" height=\"210.6px\" \/><\/p>\r\n<p class=\"import-Normal\">Let us examine how this program works.<\/p>\r\n\r\n<table>\r\n<tbody>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>testScore = float(input(\"Enter a test score from 0 to 100: \"))<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">Accept a numeric test grade from the user as a string and convert the number to a floating point values. Save this value in a variable named <code>\u201ctestScore\u201d<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>if testScore &gt;= 90:<\/code>\r\n<code><span style=\"font-family: inherit;font-size: inherit\">\u00a0 \u00a0 print(\"your grade is A\")<\/span><\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The first branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 90) is <code>true<\/code> then we print the letter grade \u201cA\u201d using the <code>print<\/code> function and end the program. If the condition is <code>false<\/code>, the program continues to the next branch (the first <code>elif<\/code> condition).<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>elif testScore &gt;= 80:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is B\")<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The second branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 80) is <code>true<\/code> then we print the letter grade \u201cB\u201d using the <code>print<\/code> function and end the program. If the condition is <code>false,<\/code> the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 90 .This was determined in the first branch (the previous <code>if<\/code> condition). Therefore we know that the score MUST be less than 90.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>elif testScore &gt;= 70:<\/code>\r\n<code><span style=\"font-family: inherit;font-size: inherit\">\u00a0 \u00a0 print(\"your grade is C\")<\/span><\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The third branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 70) is <code>true<\/code> then we print the letter grade \u201cC\u201d and end the program. If the condition is <code>false<\/code>, the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 80 . Therefore we know that the score MUST be less than 80.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>elif testScore &gt;= 60:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is D\")<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The fourth branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 60) is <code>true<\/code> then we print the letter grade \u201cD\u201d and end the program. If the condition is <code>false<\/code>, the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 70 . Therefore we know that the score MUST be less than 70.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"your grade is F\")<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The \u201c<code>else<\/code>\u201d is the final branch of the chained conditional statement. In order to execute this branch ALL previous conditions must have been evaluated to \u201c<code>false<\/code>\u201d. Note that this statement will not be executed if the test score is above a 60.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr>\r\n<td><\/td>\r\n<td><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p class=\"import-Normal\">One conditional can also be nested within another called <strong>nested conditionals<\/strong>. Earlier in this section we saw the following example using a chained conditional (<code style=\"font-weight: bold\">if-elif-else<\/code>).<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>if x &lt; y:<\/code><\/p>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is less than y')<\/code>\r\n<code class=\"import-Normal\">elif x &gt; y:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is greater than y')<\/code>\r\n<code class=\"import-Normal\">else:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x and y are equal')<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">We could have just as easily written this code using nested conditionals like this:<\/p>\r\n\r\n<div>\r\n<div class=\"textbox\">\r\n\r\n<code>if x == y:<\/code>\r\n<code style=\"padding-left: 30px\">print('x and y are equal')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">if x &lt; y:<\/code>\r\n<code style=\"padding-left: 60px\">print('x is less than y')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print('x is greater than y')<\/code>\r\n\r\n<\/div>\r\n<\/div>\r\n<p class=\"import-Normal\">The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.<\/p>\r\n<p class=\"import-Normal\">Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.<\/p>\r\nLogical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:\r\n<div class=\"textbox\">\r\n\r\n<code>if 0 &lt; x:<\/code>\r\n<code style=\"padding-left: 30px\">if x &lt; 10:<\/code>\r\n<code style=\"padding-left: 60px\">print('x is a positive single-digit number.')<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator:<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>if 0 &lt; x and x &lt; 10:<\/code>\r\n<code style=\"padding-left: 30px\">print('x is a positive single-digit number.')<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">For this kind of condition, Python provides even a more concise option:<\/p>\r\n\r\n<div class=\"textbox\"><code class=\"import-Normal\">if 0 &lt; x &lt; 10:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is a positive single-digit number.')<\/code><\/div>\r\n<h1 class=\"import-Normal\">Exception Handling<\/h1>\r\n<p class=\"import-Normal\">In our programming experience so far we have encountered several kinds of programming run-time exceptions, such as division by zero, attempting to read a variable that has not been defined, and attempting to convert a non-number to an integer. We have seen these and other run-time exceptions immediately terminate a running program.<\/p>\r\n<p class=\"import-Normal\">Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero).<\/p>\r\n<p class=\"import-Normal\">Python provides a standard mechanism called exception handling that allows programmers to deal with these kinds of run-time exceptions and many more. Rather than always terminating the program\u2019s execution (this is called a program \u201ccrash\u201d), an executing program can detect the problem when it arises and possibly execute code to correct the issue it in some way.<\/p>\r\n<p class=\"import-Normal\">Exceptions occur when <em>exceptional situations<\/em> occur in your program. Similarly, what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error.<\/p>\r\n\r\n<h2><a id=\"_Toc519230980\"><\/a>Errors<\/h2>\r\n<p class=\"import-Normal\">Consider the simple <code>print<\/code> function call. What if we misspell <code>print<\/code> as <code>Print<\/code>? Note the capitalization. In this case, Python raises a syntax error. The following output appears in the Python shell. Observe that a <code>NameError<\/code> is raised and also the location of the error detected is printed. This is what an error handler for this error does.<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>&gt;&gt;&gt;Print(\"hello there!\")<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#0&gt;\", line 1, in &lt;module&gt; <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 Print(\"hello there!\")<\/code>\r\n<code style=\"color: #ff0000\">NameError: name 'Print' is not defined<\/code>\r\n<code>&gt;&gt;&gt; print(\"hello there!\")<\/code>\r\n<code>hello there!<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/p>\r\n\r\n<\/div>\r\n<h2><a id=\"_Toc519230981\"><\/a>Exceptions<\/h2>\r\n<p class=\"import-Normal\">Let us try to read input from the user. In the Python shell we enter the first line below and hit the Enter key. When the computer prompts for input, instead press [ctrl-c] (this example is with Windows) and see what happens.<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code>\r\n<code>&gt;&gt;&gt; text = input(\"Enter something: \")<\/code>\r\n<code>Enter something:<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#5&gt;\", line 1, in &lt;module&gt;<\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 text = input(\"Enter something: \")<\/code>\r\n<code style=\"color: #ff0000\">KeyboardInterrupt<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">Python raises an error called <code>KeyboardInterrupt<\/code> which basically means it was interrupted when it expected to get user input.<\/p>\r\nLet us look at another example. Here we will read input from the user and then attempt to convert the string input into an integer.\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; num = input(\"Enter a number between 1 and 10: \")<\/code>\r\n<code>Enter a number between 1 and 10: no<\/code>\r\n<code>&gt;&gt;&gt; int(num)<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#13&gt;\", line 1, in &lt;module&gt;<\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 int(num)<\/code>\r\n<code style=\"color: #ff0000\">ValueError: invalid literal for int() with base 10: 'no'\r\n&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">Python raises an error called <code>ValueError<\/code> which is letting us know that the string <code>\u2019no\u2019<\/code> cannot be converted to an integer value. Programmers can avoid this scenario by checking that a string\u2019s value can be converted to a number value.<\/p>\r\n<p class=\"import-Normal\">Another common exception occurs when we try to evaluate a comparison which does not make sense. Consider the following Python conditional statements executed in the Shell window:<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; 12 &gt; 5<\/code>\r\n<code>True<\/code>\r\n<code>&gt;&gt;&gt; 12 == 5<\/code>\r\n<code>False<\/code>\r\n<code>&gt;&gt;&gt; 12 &lt; 'a'<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#2&gt;\", line 1, in &lt;module&gt; <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 \u00a012 &lt; 'a'<\/code>\r\n<code style=\"color: #ff0000\">TypeError: '&lt;' not supported between instances of 'int' and 'str'<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">Python raises an error called <code>TypeError<\/code> which is letting us know that the condition <code>12 &lt; 'a'<\/code> cannot be performed.<\/p>\r\n\r\n<h2><a id=\"_Toc519230982\"><\/a>Handling Exceptions<\/h2>\r\n<p class=\"import-Normal\">Essentially, exceptions are events that modify program\u2019s flow, either intentionally or due to errors. They are special events that can occur due to an error, e.g. trying to divide a number by zero. Exceptions, by definition, don\u2019t occur very often; hence, they are the \u201cexception to the rule\u201d.<\/p>\r\n<p class=\"import-Normal\">Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. One use of exceptions is to catch an error and allow the program to continue working instead of crashing ungracefully.<\/p>\r\n<p class=\"import-Normal\">This is the most common way to use exceptions. When programming with the Python command line interpreter (in the Shell window), you don\u2019t need to worry about catching exceptions. Your program is usually short enough to not be hurt too much if an exception occurs. Plus, having the exception occur at the command line is a quick and easy way to tell if your code logic has a problem. However, if the same error occurred in your saved .py file program, it will crash (fail) and stop working.<\/p>\r\n<p class=\"import-Normal\">Exceptions can be thought of as a special form of the <code>if-else<\/code> statements. You can realistically do the same thing with <code>if<\/code> blocks as you can with exceptions. However, as already mentioned, exceptions aren\u2019t processed until they occur; <code>if<\/code> blocks are processed all the time. Proper use of exceptions can help the performance of your program. The more infrequent the error might occur, the better off you are to use exceptions; using <code>if<\/code> blocks requires Python to always test extra conditions before continuing. Exceptions also make code management easier: if your programming logic is mixed in with error-handling <code>if<\/code> statements, it can be difficult to read, modify, and debug your program.<\/p>\r\n<p class=\"import-Normal\">We can handle exceptions using the <code>try-except-else<\/code> statement. Briefly, <code>try<\/code> creates a block that attempts to perform an action. If that action fails, the <code>except<\/code> block catches any exception that is raised and notifies the user that an error occurred, then stops executing the program. If the code within the try block does not produce an exception, the program\u2019s execution continues with code in the <code>else<\/code> block.<\/p>\r\n\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230983\"><\/a><span class=\"import-Heading3Char\">Practice<\/span> - Here is a simple program that uses exception processing. It simply produces the quotient of 2 numbers. Try entering, saving and running the following program (<code>exceptionHandling.py<\/code>).<\/h2>\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code># exception handling<\/code>\r\n<code>first_number = input ( \"Enter the first number: \") #gets input from keyboard<\/code>\r\n<code>sec_number = input ( \"Enter the second number: \" )<\/code>\r\n<code>try :<\/code>\r\n<code style=\"padding-left: 30px\">num1 = float( first_number ) #try turning keyboard input into floats<\/code>\r\n<code style=\"padding-left: 30px\">num2 = float( sec_number )<\/code>\r\n<code style=\"padding-left: 30px\">result = num1\/num2 #try dividing num1 by num2<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"Error: enter numbers only; num2 cannot equal zero\")<\/code>\r\n<code>else :<\/code>\r\n<code style=\"padding-left: 30px\">print(str(num1) + \"\/\" + str(num2) + \"=\" + str(result))<\/code><\/p>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">The output from executing this program, three separate times, is shown below.<\/p>\r\n\r\n<div class=\"textbox\"><code>\u00a0RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code>\r\n<code style=\"color: #333399\">Enter the first number: 33<\/code>\r\n<code style=\"color: #333399\">Enter the second number: 22<\/code>\r\n<code style=\"color: #333399\">33.0\/22.0=1.5<\/code>\r\n<code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code>\r\n<code style=\"color: #000080\">Enter the first number: 33<\/code>\r\n<code style=\"color: #000080\">Enter the second number: twenty<\/code>\r\n<code style=\"color: #000080\">Error: enter numbers only; num2 cannot equal zero<\/code>\r\n<code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code>\r\n<code style=\"color: #ff9900\">Enter the first number: 33<\/code>\r\n<code style=\"color: #ff9900\">Enter the second number: 0<\/code>\r\n<code style=\"color: #ff9900\">Error: enter numbers only; num2 cannot equal zero<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">In this example we simply print out a message to the user in the except block and then gracefully terminate our program. We use the <code>else<\/code> statement at the end to perform the rest of the program logic if all goes well. As stated before, the whole try block could also have been written as <code>if\/else<\/code> statements but that would have required Python to process each statement to see if they matched. By using exceptions, the \u201cdefault\u201d case is assumed to be true until an exception actually occurs. This speeds up processing.<\/p>\r\n<p class=\"import-Normal\">It\u2019s better to include error-checking, such as exceptions, in your code as you program rather than as an afterthought. A special \u201ccategory\u201d of programming involves writing test cases (we wrote test cases for our algorithms in Unit 1!) to ensure that most possible errors are accounted for in the code, especially as the code changes or new versions are created. Recall the test cases we were introduced to when writing our algorithms in Unit 1. By planning ahead and putting exception handling into your program at the outset, you ensure that problems are caught before they can cause problems.<\/p>\r\n<p class=\"import-Normal\">Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero).<\/p>\r\n\r\n<h1><a id=\"_Toc519230984\"><\/a>Practice with Handling Exceptions in our Programs<\/h1>\r\n<p class=\"import-Normal\">Let us review some examples of handling exceptions in some of our programs we have written.<\/p>\r\n\r\n<h2><span class=\"import-Heading3Char\">Practice #1<\/span> - Calculating the distance between two points:<\/h2>\r\n<div class=\"textbox\">\r\n\r\n<code># calculates the distance between two points<\/code>\r\n\r\n<code>import math<\/code>\r\n\r\n<code>print(\"This program calculates the distance between two points.\")<\/code>\r\n<code>print() #print a blank line<\/code>\r\n\r\n<code>x1 = float(input(\"Enter the x for the first point: \"))<\/code>\r\n<code>y1 = float(input(\"Enter the y for the first point: \"))<\/code>\r\n<code>print()<\/code>\r\n<code>x2 = float(input(\"Enter the x for the second point: \"))<\/code>\r\n<code>y2 = float(input(\"Enter the y for the second point: \"))<\/code>\r\n\r\n<code>distance = math.sqrt((x2-x1)**2\u00a0 + (y2-y1)**2)<\/code>\r\n\r\n<code>print()<\/code>\r\n<code>print(\"The distance between the points is\", distance)<\/code>\r\n\r\n<\/div>\r\nThe output when executing this program with non-numeric input is seen below:\r\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART:<\/code>\r\n<code>C:\/Users\/lh166266.UALBANY\/distanceBetweenPointsExceptionHandling.py<\/code>\r\n<code style=\"color: #333399\">This program calculates the distance between two points.<\/code>\r\n<code style=\"color: #333399\">Enter the x for the first point: 17<\/code>\r\n<code style=\"color: #333399\">Enter the y for the first point: 23<\/code>\r\n<code style=\"color: #333399\">Enter the x for the second point: 88<\/code>\r\n<code style=\"color: #333399\">Enter the y for the second point: 9p<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"C:\\Users\\lh166266.UALBANY\\distanceBetweenPoints.py\", line 12, in &lt;module&gt; <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 y2 = float(input(\"Enter the y for the second point: \"))<\/code>\r\n<code style=\"color: #ff0000\">ValueError: could not convert string to float: '9p'<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">Rewrite this program to include exception handling to catch the <code>ValueError<\/code> when we try and convert our user input into floating point numbers.<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code># Calculates the distance between two points<\/code><\/p>\r\n<code>import math<\/code>\r\n\r\n<code>print(\"This program calculates the distance between two points.\")<\/code>\r\n<code>print()<\/code>\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">x1 = float(input(\"Enter the x for the first point: \"))<\/code>\r\n<code style=\"padding-left: 30px\">y1 = float(input(\"Enter the y for the first point: \"))<\/code>\r\n<code style=\"padding-left: 30px\">print()<\/code>\r\n<code style=\"padding-left: 30px\">x2 = float(input(\"Enter the x for the second point: \"))<\/code>\r\n<code style=\"padding-left: 30px\">y2 = float(input(\"Enter the y for the second point: \"))<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"Error: enter numeric values only\")<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)<\/code>\r\n<code style=\"padding-left: 30px\">print()<\/code>\r\n<code style=\"padding-left: 30px\">print(\"The distance between the points is\", distance)<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">The output when executing the revised program with non-numeric input is far more user friendly!<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART:<\/code>\r\n<code>C:\/Users\/lh166266.UALBANY\/distanceBetweenPointsExceptionHandling.py<\/code>\r\n<code style=\"color: #000080\">This program calculates the distance between two points.<\/code>\r\n<code style=\"color: #000080\">Enter the x for the first point: 17<\/code>\r\n<code style=\"color: #000080\">Enter the y for the first point: 23<\/code>\r\n<code style=\"color: #000080\">Enter the x for the second point: 88<\/code>\r\n<code style=\"color: #000080\">Enter the y for the second point:9p<\/code>\r\n<code style=\"color: #000080\">Error: enter numeric values only<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/p>\r\n\r\n<\/div>\r\n<h2><span class=\"import-Heading3Char\">Practice #<\/span><span class=\"import-Heading3Char\">2<\/span> \u2013 Guess the Number:<\/h2>\r\n<div class=\"textbox\">\r\n\r\n<code>number = 23<\/code>\r\n<code>guess = int(input('Enter an integer : '))<\/code>\r\n<code>if guess == number:<\/code>\r\n<code style=\"padding-left: 30px\">print('Congratulations, you guessed it.')<\/code>\r\n<code style=\"padding-left: 30px\">print('(but you do not win any prizes!)')<\/code>\r\n<code>elif guess &lt; number:<\/code>\r\n<code style=\"padding-left: 30px\">print('No, it is a little higher than that')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print('No, it is a little lower than that')<\/code>\r\n\r\n<code>print('Done')<\/code>\r\n\r\n<\/div>\r\nThe output when executing this program with non-numeric input is seen below:\r\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/ifElse.py<\/code>\r\n<code style=\"color: #000080\">Enter an integer : 8g6<\/code>\r\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"C:\\Users\\lh166266.UALBANY\\Dropbox\\OER Textbook\\TEXTBOOK OER\\Code\\ifElse.py\", line 2, in &lt;module&gt; <\/code>\r\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 guess = int(input('Enter an integer : '))<\/code>\r\n<code style=\"color: #ff0000\">ValueError: invalid literal for int() with base 10: '8g6'\r\n&lt;\/span style=\"color: #ff0000;\"&gt;&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\">Rewrite this program to include exception handling to catch the <code>ValueError<\/code> when we try and convert the user input into an integer.<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code># Guess my number<\/code>\r\n\r\n<code>number = 23 .\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0#this is \u2018my number\u2019<\/code>\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">guess = int(input('Enter an integer : '))<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"ERROR: enter whole numbers only\")<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">if guess == number:<\/code>\r\n<code style=\"padding-left: 60px\">print('Congratulations, you guessed it.')<\/code>\r\n<code style=\"padding-left: 60px\">print('(but you do not win any prizes!)')<\/code>\r\n<code style=\"padding-left: 30px\">elif guess &lt; number:<\/code>\r\n<code style=\"padding-left: 60px\">print('No, it is a little higher than that')<\/code>\r\n<code style=\"padding-left: 30px\">else:<\/code>\r\n<code style=\"padding-left: 60px\">print('No, it is a little lower than that')<\/code>\r\n\r\n<code>print('Done')<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">The output when executing the revised program with non-numeric input gracefully ends rather than crashing!<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/ifElseExceptionHandling.py<\/code>\r\n<code style=\"color: #003366\">Enter an integer : 88m<\/code>\r\n<code style=\"color: #003366\">ERROR: enter whole numbers only<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<h1><a id=\"_Toc519230987\"><\/a>Iteration<\/h1>\r\n<p class=\"import-Normal\">This section is about iteration, which is the ability to run a block of statements repeatedly. Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.<\/p>\r\n\r\n<h2><a id=\"_Toc519230988\"><\/a>The while Statement<\/h2>\r\n<p class=\"import-Normal\">A <code>while<\/code> statement is an iterative control statement that repeatedly executes a set of statements based on a provided Boolean expression (condition). All iterative control needed in a program can be achieved by use of the <code>while<\/code> statement, though, as we will see later, other iterative control statements can be more useful for solving some computational problems.<\/p>\r\nHere is a version of a countdown function that uses a while statement:\r\n<div class=\"textbox\">\r\n\r\n<code>def countdown(n):<\/code>\r\n<code style=\"padding-left: 30px\">while n &gt; 0:<\/code>\r\n<code style=\"padding-left: 60px\">print(n)<\/code>\r\n<code style=\"padding-left: 60px\">n = n - 1<\/code>\r\n<code style=\"padding-left: 30px\">print('Blastoff!')<\/code>\r\n\r\n<\/div>\r\n\r\n[caption id=\"\" align=\"aligncenter\" width=\"371\"]<img class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161439\/image47.png\" alt=\"image\" width=\"371\" height=\"376\" \/> Figure 45: While Loop Flowchart[\/caption]\r\n\r\n<small>\u00a0<\/small>You can almost read the <code>while<\/code> statement as if it were English. It means, \u201cWhile n is greater than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!\u201d\r\n<p class=\"import-Normal\">Here is the flow of execution for a while statement:<\/p>\r\n\r\n<ol>\r\n \t<li>Determine whether the condition is true or false.<\/li>\r\n \t<li>If false, exit the while statement and continue execution at the next statement.<\/li>\r\n \t<li>If the condition is true, run the body and then go back to step 1.<\/li>\r\n<\/ol>\r\n<p class=\"import-Normal\">This type of flow is called a loop because the third step loops back around to the top.<\/p>\r\n<p class=\"import-Normal\">The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an <strong>infinite<\/strong> loop.<\/p>\r\n<p class=\"import-Normal\">In the case of the countdown function, we can prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.<\/p>\r\n\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230989\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 1<\/span>: Try executing the following program which uses the countdown function (<code>countdown.py<\/code>).<\/h2>\r\n<div class=\"textbox\">\r\n\r\n<code>def countdown(n):<\/code>\r\n<code style=\"padding-left: 30px\">while n &gt; 0:<\/code>\r\n<code style=\"padding-left: 60px\">print(n)<\/code>\r\n<code style=\"padding-left: 60px\">n = n - 1<\/code>\r\n<code style=\"padding-left: 30px\">print('Blastoff!')<\/code>\r\n<code>num = input(\"enter a positive number to countdown from: \")<\/code>\r\n\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">num=int(num)<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"ERROR: enter a whole number\")<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">countdown(num)<\/code>\r\n\r\n<\/div>\r\nAn example of the output after execution:\r\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/countdown.py<\/code>\r\n<code style=\"color: #003366\">enter a number to countdown from: 9<\/code>\r\n<code style=\"color: #003366\">9<\/code>\r\n<code style=\"color: #003366\">8<\/code>\r\n<code style=\"color: #003366\">7<\/code>\r\n<code style=\"color: #003366\">6<\/code>\r\n<code style=\"color: #003366\">5<\/code>\r\n<code style=\"color: #003366\">4<\/code>\r\n<code style=\"color: #003366\">3<\/code>\r\n<code style=\"color: #003366\">2<\/code>\r\n<code style=\"color: #003366\">1<\/code>\r\n<code> style=\"color: #003366;\"&gt;Blastoff!<\/code>\r\n<code>&gt;&gt;<\/code>&gt;<\/div>\r\n<p class=\"import-Normal\">The variable <code style=\"font-weight: bold\">n<\/code> in the <code>countdown.py<\/code> program is referred to as a <em>counter<\/em>. A <em>counter<\/em> variable is used to count something, usually initialized to zero and then incremented (or decremented) and is commonly used in programs.<\/p>\r\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>while<\/code> statement allows you to repeatedly execute a block of statements as long as a condition is true. A <code>while<\/code> statement is an example of what is called a <em lang=\"en\" xml:lang=\"en\">looping<\/em><span lang=\"en\" xml:lang=\"en\"> statement. A <\/span><code>while<\/code><span lang=\"en\" xml:lang=\"en\"> statement can have an optional else clause.<\/span><span lang=\"en\" xml:lang=\"en\"> Let us look at the following program (<\/span><code>while.py<\/code>)<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>number = 23<\/code>\r\n<code>running = True<\/code>\r\n\r\n<code>while running:<\/code>\r\n<code style=\"padding-left: 30px\">guess = int(input('Enter an integer : '))<\/code>\r\n<code style=\"padding-left: 30px\">if guess == number:<\/code>\r\n<code style=\"padding-left: 60px\">print('Congratulations, you guessed it.')<\/code>\r\n<code style=\"padding-left: 60px\"># this causes the while loop to stop<\/code>\r\n<code style=\"padding-left: 60px\">running = False<\/code>\r\n<code style=\"padding-left: 30px\">elif guess &lt; number:<\/code>\r\n<code style=\"padding-left: 60px\">print('No, it is a little higher than that.')<\/code>\r\n<code style=\"padding-left: 30px\">else:<\/code>\r\n<code style=\"padding-left: 60px\">print('No, it is a little lower than that.')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print('The while loop is over.')<\/code>\r\n<code style=\"padding-left: 30px\"># Do anything else you want to do here<\/code>\r\n\r\n<code>print('Done')<\/code>\r\n\r\n<\/div>\r\n<\/div>\r\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly run the program for each guess, as we have done in the previous section. This aptly demonstrates the use of the <\/span><code>while<\/code><span lang=\"en\" xml:lang=\"en\"> statement.<\/span>Let us examine more closely the code in this program <span lang=\"en\" xml:lang=\"en\">(<\/span><code>while.py<\/code><span lang=\"en\" xml:lang=\"en\">)<\/span>.<\/p>\r\n\r\n<table style=\"height: 1172px\">\r\n<tbody>\r\n<tr class=\"TableGrid-R\" style=\"height: 73px\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 188px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 188px\">\r\n<p class=\"import-Normal\"><code>number = 23<\/code><\/p>\r\n<p class=\"import-Normal\"><code>running = True<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 188px\">\r\n<p class=\"import-Normal\">We set the variable number to a number we want; here we choose the number \u201823\u2019.The variable running is referred to as a \u2018flag\u2019 variable. Flag variables go by many different names, but they all represent a variable (usually of <code>Boolean<\/code> type) that can only be one of two states, <code>True<\/code> or <code>False<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 208px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 208px\">\r\n<p class=\"import-Normal\"><code>while running<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 208px\">\r\n<p class=\"import-Normal\">This where the loop starts.<\/p>\r\n<p class=\"import-Normal\">First, we check if the variable <code>running<\/code> is <code>True<\/code> and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the <code>running<\/code> variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 604px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 604px\">\r\n<p class=\"import-Normal\"><code>guess =<\/code> <code>int(input('Enter an integer : '))<\/code><\/p>\r\n<p class=\"import-Normal\"><code>if guess == number:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print('Congratulations, you guessed it.')<\/code><\/p>\r\n<p class=\"import-Normal\"><code>running = False<\/code><\/p>\r\n<p class=\"import-Normal\"><code>elif guess &lt; number:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print('No, it is a little higher than that.')<\/code><\/p>\r\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print('No, it is a little lower than that.')<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 604px\">\r\n<p class=\"import-Normal\">This is the \u2018body\u2019 of the entire loop.<\/p>\r\n<p class=\"import-Normal\">The user is asked to enter an integer number which is converted into an integer and saved in the variable <code>guess<\/code>.<\/p>\r\n<p class=\"import-Normal\">Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message and set our flag variable, <code>running<\/code>, to <code>False<\/code>. This will soon cause the while loop to stop.<\/p>\r\n<p class=\"import-Normal\">Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that.<\/p>\r\n<p class=\"import-Normal\">Finally we check if the guess is greater than the number, and if so, we inform the user that they must guess a little lower than that.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 99px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 99px\">\r\n<p class=\"import-Normal\"><code>print('Done')<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 99px\">\r\n<p class=\"import-Normal\">Once we have exited the while loop we print this single statement to indicate to the user that the guessing game is over.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p class=\"import-Normal\">The following is a sample of output after running this program:<\/p>\r\n\r\n<div class=\"textbox\"><code style=\"color: #003366\">Enter an integer : 5<\/code>\r\n<code style=\"color: #003366\">No, it is a little higher than that.<\/code>\r\n<code style=\"color: #003366\">Enter an integer : 19<\/code>\r\n<code style=\"color: #003366\">No, it is a little higher than that.<\/code>\r\n<code style=\"color: #003366\">Enter an integer:25 <\/code>\r\n<code style=\"color: #003366\">No, it is a little lower than that.<\/code>\r\n<code style=\"color: #003366\">Enter an integer:24<\/code>\r\n<code style=\"color: #003366\">No, it is a little lower than that.<\/code>\r\n<code style=\"color: #003366\">Enter an integer: 23<\/code>\r\n<code style=\"color: #003366\">Congratulations, you guessed it.<\/code>\r\n<code style=\"color: #003366\">The while loop is over. Done<\/code>\r\n&gt;&gt;&gt;<\/div>\r\n<p class=\"import-Normal\">This is an example of an <em>interactive loop<\/em> because it allows the user to repeat something (in this example the user is guessing a number) on demand.<\/p>\r\n\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230990\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 2<\/span>: The following program allows a user to enter any number of nonnegative integers. When the user enters a negative value, the program no longer accepts input, and it displays the sum of all the nonnegative values. If a negative number is the first entry, the sum is zero. This is also an example of <em>interactive loop<\/em>. [<code>addNonNegatives.py<\/code>]<\/h2>\r\n<div class=\"textbox\"><code># Allow the user to enter a sequence of nonnegative integers to sum.<\/code>\r\n<code>entry = 0\u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code> # Ensure the loop is entered<\/code>\r\n<code>sum = 0<\/code>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># Initialize sum<\/code>\r\n<code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code>\r\n<code>while entry &gt;= 0:\u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># A negative number exits the loop<\/code>\r\n<code>entry = int(input(\"number: \")) # Get the value<\/code>\r\n<code>if entry &gt;= 0:\u00a0 \u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code># Is number nonnegative?<\/code>\r\n<code>sum = sum entry<\/code>\r\n<code>print(\"Sum =\", sum)<\/code>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># Display the sum<\/code><\/div>\r\n<div class=\"textbox\"><code>RESTART:C:\/Users\/lh166266.UALBANY\/Code\/addNonNegatives.py<\/code>\r\n<code style=\"color: #000080\">Enter positive numbers to sum (entering a negative number ends the program).<\/code>\r\n<code style=\"color: #000080\">number: 8 <\/code>\r\n<code style=\"color: #000080\">number: 9<\/code>\r\n<code style=\"color: #000080\">number: 1<\/code>\r\n<code style=\"color: #000080\">number: 2<\/code>\r\n<code style=\"color: #000080\">number: -9<\/code>\r\n<code style=\"color: #000080\">Sum = 20<\/code><\/div>\r\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 46: Sample Output from addNonNegatives.py<\/em><\/p>\r\n\r\n\r\n[caption id=\"\" align=\"alignnone\" width=\"520\"]<img class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161441\/image48.png\" alt=\"image\" width=\"520\" height=\"595\" \/> Figure 47: While Loop Flowchart[\/caption]\r\n\r\n<small>\u00a0<\/small>Let us examine more closely the code in this program.\r\n<table style=\"height: 485px\">\r\n<tbody>\r\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 154.625px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 729.625px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 73px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px;width: 154.625px\">\r\n<p class=\"import-Normal\"><code>entry = 0<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px;width: 729.625px\">\r\n<p class=\"import-Normal\">In the beginning we initialize <code>entry<\/code> to zero for the sole reason that we want the condition <code>entry &gt;= 0<\/code> of the while statement to be <code>true<\/code> initially. If we fail to initialize <code>entry<\/code>, the program will produce a run-time error when it attempts to compare <code>entry<\/code> to zero in the while condition. The <code>entry<\/code> variable holds the number entered by the user. Its value can change each time through the loop.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 75px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 75px;width: 154.625px\">\r\n<p class=\"import-Normal\"><code>sum = 0<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 75px;width: 729.625px\">\r\n<p class=\"import-Normal\">The variable <code>sum<\/code> is known as an <em>accumulator<\/em> because it accumulates each value the user enters. We initialize <code>sum<\/code> to zero in the beginning because a value of zero indicates that it has not accumulated anything. If we fail to initialize <code>sum<\/code>, the program will generate a run-time error when it attempts to use the + operator to modify the (non-existent) variable.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 89px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 89px;width: 154.625px\">\r\n<p class=\"import-Normal\"><code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 89px;width: 729.625px\">\r\n<p class=\"import-Normal\">This statement provides instructions for this app.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 161px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 161px;width: 154.625px\">\r\n<p class=\"import-Normal\"><code>while entry &gt;= 0:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>entry = int(input(\"number: \"))<\/code><\/p>\r\n<p class=\"import-Normal\"><code>if entry &gt;= 0:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>sum = sum + entry<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 161px;width: 729.625px\">\r\n<p class=\"import-Normal\">Within the loop we repeatedly add the user\u2019s input values to <code>sum<\/code>. When the loop finishes (because the user entered a negative number), <code>sum<\/code> holds the <code>sum<\/code> of all the nonnegative values entered by the user.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 44px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 44px;width: 154.625px\">\r\n<p class=\"import-Normal\"><code>print(\"Sum =\", sum)<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 44px;width: 729.625px\">\r\n<p class=\"import-Normal\">Once we have exited the <code>while<\/code> loop we print this single statement to indicate to the user what the sum of all the numbers entered is.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230991\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 3<\/span>: Now let us rewrite this program to add additional functionality. In addition to finding the sum of nonnegative values we will calculate the average. [<code>avgNonNegatives.py<\/code>]<\/h2>\r\n<div class=\"textbox\"><code># Allow the user to enter a sequence of nonnegative integers to sum and find the average.<\/code>\r\n<code>entry = 0\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Ensure the loop is entered<\/code>\r\n<code>sum = 0\u00a0\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 <code># Initialize sum<\/code>\r\n<code>count = 0\u00a0<\/code>\u00a0\u00a0\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\u00a0 <code># Initialize count<\/code>\r\n<code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code>\r\n<code>while entry &gt;= 0:\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 <code># A negative number exits the loop<\/code>\r\n<code>entry = int(input(\"number: \"))\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Get the value<\/code>\r\n<code>if entry &gt;= 0: \u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code>\u00a0 # Is number nonnegative?<\/code>\r\n<code>sum = sum + entry\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Only add it if it is nonnegative<\/code>\r\n<code>count = count + 1<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> #increment the count of numbers entered<\/code>\r\n<code>print(\"Sum =\", sum) # Display the sum<\/code>\r\n<code>average = sum \/ count<\/code>\r\n<code>print(\"Average =\", average)<\/code><\/div>\r\n<p class=\"import-Normal\">The program needs not only an accumulator variable (i.e. <code>sum<\/code>) but a counter variable also (named <code>count<\/code>) to keep track of how many numbers have been entered. We can then calculate the average by dividing the sum by the count.<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/avgNonNegatives.py<\/code>\r\n<code>Enter positive numbers to sum (entering a negative number ends the program).<\/code>\r\n<code style=\"color: #000080\">number:<\/code><code>12<\/code>\r\n<code style=\"color: #000080\">number:<\/code><code>55<\/code>\r\n<code style=\"color: #000080\">number:<\/code><code>31<\/code>\r\n<code style=\"color: #000080\">number:<\/code><code>-11<\/code>\r\n<code style=\"color: #000080\"><\/code><code>Sum = 98<\/code>\r\n<code style=\"color: #000080\">Average = 32.666666666666664<\/code><\/p>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 48: Sample Output from avgNonNegatives.py<\/em><\/p>\r\n\r\n<h2><a id=\"_Toc519230992\"><\/a>The break Statement<\/h2>\r\n<p class=\"import-Normal\">Sometimes you don\u2019t know it\u2019s time to end a loop until you get half way through the body. In that case you can use the <code>break<\/code> statement to jump out of the loop.<\/p>\r\nFor example, suppose you want to take input from the user until they type <code>done<\/code>. You could write:\r\n<div class=\"textbox\"><code>while True:<\/code>\r\n<code>line = input('&gt; ')<\/code>\r\n<code>if line == 'done':<\/code>\r\n<code>break<\/code>\r\n<code>print(line)print('Done!')<\/code><\/div>\r\n<p class=\"import-Normal\">The loop condition is <code>True<\/code>, which is always true, so the loop runs until it hits the <code>break<\/code> statement.<\/p>\r\nEach time through, it prompts the user with an angle bracket. If the user types done, the <code>break<\/code> statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here\u2019s a sample run:\r\n<div class=\"textbox\"><code>&gt; hello<\/code>\r\n<code>hello<\/code>\r\n<code>&gt; done<\/code>\r\n<code>Done!<\/code><\/div>\r\n<p class=\"import-Normal\">This way of writing <code>while<\/code> loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (\u201cstop when this happens\u201d) rather than negatively (\u201ckeep going until that happens\u201d).<\/p>\r\n<p class=\"import-Normal\">Note that the <code>break<\/code> statement works with the for loop as well.<\/p>\r\n\r\n<h2><a id=\"_Toc519230993\"><\/a>The continue Statement<\/h2>\r\n<p class=\"import-Normal\">The <code>continue<\/code> statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.<\/p>\r\nLet us examine the following example (save as <code>continue.py<\/code>):\r\n<div class=\"textbox\">\r\n\r\n<code># user is to enter a string of at minimum 3 words<\/code>\r\n<code># to end the user is to enter the word 'quit'<\/code>\r\n<code>while True:<\/code>\r\n<code><code style=\"padding-left: 30px\">data = input('Enter at least 3 words: ')<\/code><\/code>\r\n<code><code style=\"padding-left: 30px\">if data == 'quit':<\/code><\/code>\r\n<code><code style=\"padding-left: 60px\">break<\/code><\/code>\r\n<code><code style=\"padding-left: 30px\">if len(data) &lt; 3:<\/code><\/code>\r\n<code><code style=\"padding-left: 60px\">print('Too small')<\/code><\/code>\r\n<code><code style=\"padding-left: 60px\">continue<\/code><\/code>\r\n<code>print('Input (data) is of sufficient length')<\/code>\r\n<code># Do other kinds of processing here...<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">Sample Output:<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code>\r\n<code>RESTART:C:\/Users\/lh166266.UALBANY\/Code\/continue.py<\/code>\r\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> hi<\/code>\r\n<code><code style=\"color: #000080\">Too small<\/code><\/code>\r\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> how are you<\/code>\r\n<code><code style=\"color: #000080\">Input (data) is of sufficient length<\/code><\/code>\r\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> quit<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\nIn this program, we accept input from the user, but we process the input string only if it is at least 3 words long or the user enters the word \u2018quit\u2019. So, we use the built-in <code>len<\/code> function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the <code>continue<\/code> statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing we want to do here. When the user enters the word \u2018<code>quit\u2019<\/code> we exit the loop using the <code>break<\/code> statement, then end the program. This is an example of an <em>input validation loop<\/em>. In an <em>input validation loop<\/em> (commonly designed using the <code>while<\/code> loop) the program inspects user input before it is processed by the program and if input is invalid it prompts user to enter correct data.\r\n<p class=\"import-Normal\">Note that the <code>continue<\/code> statement works with the <code>for<\/code> loop as well.<\/p>\r\n\r\n<h1><a id=\"_Toc519230994\"><\/a>The for...in Statement<\/h1>\r\n<p class=\"import-Normal\">The <code>for..in<\/code> statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. Recall that a sequence is just an ordered collection of items. Let us look at the following program, <code>for.py<\/code>.<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>for i in range(1, 5):<\/code>\r\n<code><code style=\"padding-left: 30px\">print(i)<\/code><\/code>\r\n<code>else:<\/code>\r\n<code><code style=\"padding-left: 30px\">print('The for loop is over')<\/code><\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">This is what the output of the program looks like in the Python shell after it runs:<\/p>\r\n\r\n<div class=\"textbox\"><code>1<\/code>\r\n<code>2<\/code>\r\n<code>3<\/code>\r\n<code>4<\/code>\r\n<code>The for loop is over<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> function.<\/span><\/p>\r\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">What we do here is supply it two numbers and <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> returns a sequence of numbers starting from the first number and up to the second number. For example, <\/span><span lang=\"en\" xml:lang=\"en\"><code>range<\/code>(<code>1,5<\/code>)<\/span><span lang=\"en\" xml:lang=\"en\"> gives the sequence <\/span><span lang=\"en\" xml:lang=\"en\"><code>[1, 2, 3, 4]<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> By default, <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> takes a step count of <code>1<\/code>. If we supply a third number to <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\">, then that becomes the step count. For example<\/span><span lang=\"en\" xml:lang=\"en\">, <code>range(1,5,2)<\/code><\/span><span lang=\"en\" xml:lang=\"en\"> gives <\/span><span lang=\"en\" xml:lang=\"en\"><code>[1,3]<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> Remember that the <\/span><code>range<\/code><span lang=\"en\" xml:lang=\"en\"> extends up to the second number i.e. it does not include the second number.<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop then iterates over this range - <\/span><code>for i in range(1,5)<\/code><span lang=\"en\" xml:lang=\"en\"> is equivalent to <\/span><code>for i in [1, 2, 3, 4]<\/code><span lang=\"en\" xml:lang=\"en\">which is like assigning each number (or object) in the sequence to <\/span><span lang=\"en\" xml:lang=\"en\"><code>i<\/code>,<\/span><span lang=\"en\" xml:lang=\"en\"> one at a time, and then executing the block of statements for each value of <\/span><span lang=\"en\" xml:lang=\"en\"><code>i<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> In this case, we just print the value in the block of statements.<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The general form of the <code>range<\/code> expression is <\/span><code>range( begin,end,step )<\/code><span lang=\"en\" xml:lang=\"en\"> where<\/span><\/p>\r\n\r\n<ul>\r\n \t<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>begin<\/code><span lang=\"en\" xml:lang=\"en\"> is the first value in the range; if omitted, the default value is 0<\/span><\/li>\r\n \t<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>end<\/code><span lang=\"en\" style=\"text-align: initial;font-size: 1em\" xml:lang=\"en\"> is one past the last value in the range; the end value is always required and may not be omitted<\/span><\/li>\r\n \t<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>step<\/code><span lang=\"en\" style=\"text-align: initial;font-size: 1em\" xml:lang=\"en\"> is the amount to increment or decrement; if the step parameter is omitted, it defaults to 1 (counts up by ones)<\/span><\/li>\r\n<\/ul>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>begin<\/code><span lang=\"en\" xml:lang=\"en\">, <\/span><code>end<\/code><span lang=\"en\" xml:lang=\"en\">, and <code>step<\/code> must all be integer expressions; floating-point expressions and other types are not allowed. The arguments in the range expression may be literal numbers (like 10), variables (like<\/span><span lang=\"en\" xml:lang=\"en\"> x<\/span><span lang=\"en\" xml:lang=\"en\">, if <\/span><span lang=\"en\" xml:lang=\"en\">x<\/span><span lang=\"en\" xml:lang=\"en\"> is <\/span><span lang=\"en\" xml:lang=\"en\">equal<\/span><span lang=\"en\" xml:lang=\"en\"> to an integer), and arbitrarily complex integer expressions.<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>range<\/code><span lang=\"en\" xml:lang=\"en\"> expression is very flexible. Consider the following loop that counts down from 21 to 3 by threes:<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code>for n in range(21, 0, -3):\r\nprint(n, end=' ')<\/code>\r\n\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">It prints: <\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff;text-indent: 36pt\"><code>21 18 15 12 9 6 3<\/code><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">Thus <\/span><code>range(21, 0, -3)<\/code><span lang=\"en\" xml:lang=\"en\"> represents the sequence <\/span><span lang=\"en\" xml:lang=\"en\"><code>21;18;15;12;9; 3<\/code>.<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The expression <\/span><code>range(1000)<\/code><span lang=\"en\" xml:lang=\"en\"> produces the sequence <\/span><code>0;1;2; : : : ; 999.<\/code><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The following code computes and prints the sum of all the positive integers less than 100:<\/span><\/p>\r\n<code style=\"padding-left: 30px\">sum = 0 # Initialize sum<\/code>\r\n<code style=\"padding-left: 30px\">for i in range(1, 100):<\/code>\r\n<code style=\"padding-left: 60px\">sum += i<\/code>\r\n<code style=\"padding-left: 60px\">print(sum)<\/code>\r\n\r\n<span lang=\"en\" xml:lang=\"en\">Remember that the <\/span><code>else<\/code> <span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> is optional. When included, it is always executed once after the <\/span><span lang=\"en\" xml:lang=\"en\">for<\/span><span lang=\"en\" xml:lang=\"en\"> loop is over unless a <\/span><a class=\"rId98\" href=\"#break-statement\"><code>break<\/code><\/a><span lang=\"en\" xml:lang=\"en\"> statement is encountered.<\/span>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\">So far we have used the <code>for<\/code> loop to iterate over integer sequences because this is a useful and common task in developing apps. The <code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop, however, can iterate over any iterable object<\/span><span lang=\"en\" xml:lang=\"en\">, such as a string<\/span><span lang=\"en\" xml:lang=\"en\">.<\/span><\/p>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">We can use a <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop to iterate over the characters that comprise a string. <\/span><span lang=\"en\" xml:lang=\"en\">The following program<\/span><span lang=\"en\" xml:lang=\"en\"> uses a <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop to print the individual characters of a string<\/span><code> (printLetters.py<span lang=\"en\" xml:lang=\"en\">)<\/span><\/code><span lang=\"en\" xml:lang=\"en\">.<\/span><\/p>\r\n<code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code lang=\"en\" xml:lang=\"en\">word = input('Enter a word: ')<\/code><\/code>\r\n<code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code lang=\"en\" xml:lang=\"en\">for letter in word:<\/code><\/code>\r\n<code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt;padding-left: 30px\"><code lang=\"en\" xml:lang=\"en\"> print(letter)<\/code><\/code>\r\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">Sample output<\/span><span lang=\"en\" xml:lang=\"en\">: <\/span><\/p>\r\n\r\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/printLetters.py<\/code>\r\n<code style=\"color: #000080\">Enter a word: hello<\/code>\r\n<code style=\"color: #000080\">h<\/code>\r\n<code style=\"color: #000080\">e<\/code>\r\n<code style=\"color: #000080\">l<\/code>\r\n<code style=\"color: #000080\">l<\/code>\r\n<code style=\"color: #000080\">o<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n&nbsp;\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230995\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 1<\/span>: Write a program to solve the following problem. <code>[printWords.py]<\/code><\/h2>\r\n<div class=\"textbox\">Problem: Ask the user how many words they want to enter then print the words entered by the user on one line separated by spaces.\r\nInput: Number of words to be entered; this value must be a positive integer greater than zero.<\/div>\r\n&nbsp;\r\n<div class=\"textbox\">\r\n\r\n<code># Ask the user how many words they want to enter<\/code>\r\n<code># then print the words together on one line.<\/code>\r\n<code>sentence = \"\"<\/code>\r\n<code>num = input(\"How many words do you want to enter? \")<\/code>\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">num=int(num)<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print (\"ERROR: enter a number\")<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">if num &gt; 0: #check for a positive number<\/code>\r\n<code style=\"padding-left: 60px\">for i in range(num):<\/code>\r\n<code style=\"padding-left: 90px\">word = input(\"enter a word: \")<\/code>\r\n<code style=\"padding-left: 90px\">sentence = sentence + \" \" + word<\/code>\r\n<code style=\"padding-left: 60px\">print(sentence)<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">print(\"Will only accept a positive integer number. Ending program\")<\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Note the error checking performed in the program:<\/p>\r\n\r\n<ul>\r\n \t<li>Ensures the user only enters integer numbers as input<\/li>\r\n \t<li>Ensures the user enters a positive integer<\/li>\r\n<\/ul>\r\n<h2 class=\"import-Normal\"><a id=\"_Toc519230996\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 2<\/span>: Write a program to solve the following problem. <code>[numWords.py]<\/code><\/h2>\r\n<div class=\"textbox\">Problem: Ask the user to enter in a complete sentence and display the number of words in the sentence.<\/div>\r\n<p class=\"import-Normal\">Unlike <span lang=\"en\" xml:lang=\"en\">the example where we<\/span><span lang=\"en\" xml:lang=\"en\"> use<\/span><span lang=\"en\" xml:lang=\"en\">d<\/span><span lang=\"en\" xml:lang=\"en\"> a <\/span><span lang=\"en\" xml:lang=\"en\">for<\/span><span lang=\"en\" xml:lang=\"en\"> loop to iterate over the characters <\/span><span lang=\"en\" xml:lang=\"en\">of a word, we need to use a string object\u2019s method to break the string into words.<\/span> <span lang=\"en\" xml:lang=\"en\">When you need to break a large string down into smaller chunks, or strings<\/span><span lang=\"en\" xml:lang=\"en\">,<\/span><span lang=\"en\" xml:lang=\"en\"> you use the <\/span><code>split()<\/code><span lang=\"en\" xml:lang=\"en\"> string method. By default, <\/span><code>split()<\/code><span lang=\"en\" xml:lang=\"en\"> takes whitespace as the delimiter.<\/span><span lang=\"en\" xml:lang=\"en\"> Try executing this program<\/span><code><span lang=\"en\" xml:lang=\"en\"> <code>(numWords.py)<\/code><\/span><\/code><\/p>\r\n\r\n<div class=\"textbox\"><code># Ask the user to enter in a complete sentence and display the number of words in the sentence.<\/code>\r\n<code>sentence = input(\"please enter an awe inspiring sentence or two: \")<\/code>\r\n<code>words = sentence.split()<\/code>\r\n<code>print(\"you entered\", len(words), \"words\")<\/code>\r\n<code>print(\"here are the individual words you entered:\", words)<\/code><\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Example output:<\/p>\r\n\r\n<div class=\"textbox\"><code style=\"color: #0000ff\">please enter an awe inspiring<\/code><code style=\"color: #0000ff\">sentence or two:<\/code><code> When I need to build a web app, I reach for the Python programming language. When I need to automate some small task on my system, I reach for Python. Python rocks!<\/code>\r\n<code style=\"color: #0000ff\">you entered 32 words<\/code>\r\n<code style=\"color: #0000ff\">here are the individual words you entered: ['When', 'I', 'need', 'to', 'build', 'a', 'web', 'app,', 'I', 'reach', 'for', 'the', 'Python', 'programming', 'language.', 'When', 'I', 'need', 'to', 'automate', 'some', 'small', 'task', 'on', 'my', 'system,', 'I', 'reach', 'for', 'Python.', 'Python', 'rocks!']<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Once you have used <code>split<\/code> to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.<\/p>\r\n\r\n<div class=\"textbox\"><code>&gt;&gt;&gt; sentence = \"Python is a general purpose programming language named after Monty Python.\"<\/code>\r\n<code>&gt;&gt;&gt; words = sentence.split()<\/code>\r\n<code>&gt;&gt;&gt; print(words)<\/code>\r\n<code style=\"color: #0000ff\">['Python', 'is', 'a', 'general', 'purpose', 'programming', 'language', 'named', 'after', 'Monty', 'Python.']<\/code>\r\n<code>&gt;&gt;&gt; print(words[9], words[3], words[6])<\/code>\r\n<code style=\"color: #0000ff\">Monty general language<\/code>\r\n&gt;&gt;&gt;<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Enhance this program to loop through each word in the list named words and print each word in uppercase on its own line <span lang=\"en\" xml:lang=\"en\">(<\/span><code>uppercaseWords.py<\/code>.<\/p>\r\n\r\n<div class=\"textbox\"><code># Ask the user to enter in a complete sentence and display each work in uppercase.<\/code>\r\n<code>sentence = input(\"please enter an awe inspiring sentence or two: \")<\/code>\r\n<code>words = sentence.split()<\/code>\r\n<code>print(\"you entered\", len(words), \"words\")<\/code>\r\n<code>print(\"here are the individual words you entered:\")for word in words:<\/code>\r\n<code>print(word.upper())<\/code><\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Example output:<\/p>\r\n\r\n<div class=\"textbox\"><code style=\"color: #0000ff\">please enter an awe inspiring sentence or two:<\/code><code>Python is a general purpose programming language named after Monty Python.<\/code>\r\n<code style=\"color: #0000ff\">you entered 11 words<\/code>\r\n<code style=\"color: #0000ff\">here are the individual words you entered:<\/code>\r\n<code style=\"color: #0000ff\">PYTHON<\/code>\r\n<code style=\"color: #0000ff\">IS<\/code>\r\n<code style=\"color: #0000ff\">A<\/code>\r\n<code style=\"color: #0000ff\">GENERAL<\/code>\r\n<code style=\"color: #0000ff\">PURPOSE<\/code>\r\n<code style=\"color: #0000ff\">PROGRAMMING<\/code>\r\n<code style=\"color: #0000ff\">LANGUAGE<\/code>\r\n<code style=\"color: #0000ff\">NAMED<\/code>\r\n<code style=\"color: #0000ff\">AFTER<\/code>\r\n<code style=\"color: #0000ff\">MONTYPYTHON.<\/code>\r\n&gt;&gt;&gt;<\/div>\r\n&nbsp;\r\n<div class=\"textbox\">\r\n\r\n<strong>How to choose between the <code>for<\/code> and <code>while<\/code> loop?<\/strong>\r\n\r\nUse a <code>for<\/code> loop if you know, before you start looping, the maximum number of times that you\u2019ll need to execute the body. For example, if you\u2019re traversing a list of elements, you know that the maximum number of loop iterations you can possibly need is \u201call the elements in the list\u201d. Or if you need to print the 12 times table, we know right away how many times the loop will need to run.\r\n\r\nSo any problem like \u201citerate this weather model for 1000 cycles\u201d, or \u201csearch this list of words\u201d, \u201cfind all prime numbers up to 10000\u201d suggest that a <code>for<\/code> loop is best.\r\n\r\nBy contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, as we did in this 3n + 1 problem, you\u2019ll need a <code>while<\/code> loop.\r\n\r\nWe call the first case <strong>definite<\/strong> <strong>iteration<\/strong> \u2014 we know ahead of time some definite bounds for what is needed. The latter case is called <strong>indefinite<\/strong> <strong>iteration<\/strong> \u2014 we\u2019re not sure how many iterations we\u2019ll need \u2014 we cannot even establish an upper bound!\r\n\r\n<\/div>\r\n&nbsp;\r\n<h1><a id=\"_Toc519230997\"><\/a>Nested Loops<\/h1>\r\n<p class=\"import-Normal\">Just like with<code>if<\/code> statements, <code>while<\/code> and <code>for<\/code> blocks can contain arbitrary Python statements, including other loops. A loop can therefore be nested within another loop. To see how nested loops work, consider a program that prints out a multiplication times tables (<code>multiplication.py<\/code>).<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>#multiplcation tables<\/code>\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">table = int(input(\"which multiplication times table do you want to<\/code>\r\nprint? (choose from 1 to 12) \"))\r\n<code style=\"padding-left: 30px\">x = table<\/code>\r\nexcept:\r\n<code style=\"padding-left: 30px\">print(\"ERROR: enter a whole number\")<\/code>\r\nelse:\r\n<code style=\"padding-left: 30px\">if table &gt; 0 and table &lt; 13:<\/code>\r\n<code style=\"padding-left: 60px\">for y in range(1, 13):<\/code>\r\n<code style=\"padding-left: 90px\">print (x,'*', y,'=', x*y)<\/code>\r\n<code style=\"padding-left: 30px\">else:<\/code>\r\n<code style=\"padding-left: 60px\">print (\"ERROR: multiplication tables can be generated from 1 to 12 only\")<\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Let us examine more closely the code in this program.<\/p>\r\n\r\n<table>\r\n<tbody>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>try:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>table = int(input(\"which multiplication times table do you want to print? (choose from 1 to 12) \"))<\/code><\/p>\r\n<p class=\"import-Normal\"><code>x = table<\/code><\/p>\r\n<p class=\"import-Normal\"><code>except:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print(\"ERROR: enter a whole number\")<\/code><\/p>\r\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>if table &gt; 0 and table &lt; 13:<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">We use the <code>try-except-else<\/code> block to catch the error of non-numeric input from the user.<\/p>\r\n<p class=\"import-Normal\">The <code>if<\/code> block following the <code>else<\/code> block assures that the user is entering a number in the correct range of <code>1<\/code> to <code>12<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>for y in range(1, 13):<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print (x,'*', y,'=', x*y)<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">The <code>for<\/code> loop is generating the multiplication times table requested from the user.The variable <code>x<\/code> represents the times-table the user requested and the variable <code>y<\/code> provides each entry in the times table. We use a loop to print the contents of each row. The outer loop controls how many total rows the program prints, and the inner loop, executed in its entirety each time the program prints a row, prints the individual elements that make up a row.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">This statement provides instructions for this app.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\r\n<p class=\"import-Normal\"><code>print (\"ERROR: multiplication tables can be generated from 1 to 12 only\")<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">This is the end of the program. This block, which prints and error message, only executes if the user did not enter a number in the correct range of 1 to 12.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p class=\"import-Normal\">Example output:<\/p>\r\n\r\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/multiplication.py<\/code>\r\n<code style=\"color: #0000ff\">which multiplication times table do you want to print? (choose from 1 to 12)<\/code><code>5<\/code>\r\n<code style=\"color: #0000ff\">5 * 1 = 5<\/code>\r\n<code style=\"color: #0000ff\">5 * 2 = 10<\/code>\r\n<code style=\"color: #0000ff\">5 * 3 = 15<\/code>\r\n<code style=\"color: #0000ff\">5 * 4 = 20<\/code>\r\n<code style=\"color: #0000ff\">5 * 5 = 25<\/code>\r\n<code style=\"color: #0000ff\">5 * 6 = 30<\/code>\r\n<code style=\"color: #0000ff\">5 * 7 = 35<\/code>\r\n<code style=\"color: #0000ff\">5 * 8 = 40<\/code>\r\n<code style=\"color: #0000ff\">5 * 9 = 45<\/code>\r\n<code style=\"color: #0000ff\">5 * 10 = 50<\/code>\r\n<code style=\"color: #0000ff\">5 * 11 = 55<\/code>\r\n<code style=\"color: #0000ff\">5 * 12 = 60<\/code>&gt;&gt;&gt;<\/div>\r\nNow let us consider adding to this program to generate all the multiplication times tables from 1 to 12. This is easily done with nested loops.\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>#multiplcation times tables tables<\/code>\r\n<code class=\"import-Normal\">for x in range(1, 13):<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">for y in range(1, 13):<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 60px\">print (x,'*', y,'=', x*y)<\/code><\/p>\r\n\r\n<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">The output after execution of this 3-lines-of-code program generates 144 lines of output!<\/p>\r\n\r\n<div class=\"textbox\">\r\n<p class=\"import-Normal\"><code>1 * 1 = 11 * 2 = 21 * 3 = 31 * 4 = 41 * 5 = 51 * 6 = 61 * 7 = 71 * 8 = 81 * 9 = 91 * 10 = 101 * 11 = 111 * 12 = 122 * 1 = 22 * 2 = 42 * 3 = 62 * 4 = 82 * 5 = 102 * 6 = 122 * 7 = 142 * 8 = 162 * 9 = 182 * 10 = 202 * 11 = 222 * 12 = 24...12 * 1 = 1212 * 2 = 2412 * 3 = 3612 * 4 = 4812 * 5 = 6012 * 6 = 7212 * 7 = 8412 * 8 = 9612 * 9 = 10812 * 10 = 12012 * 11 = 13212 * 12 = 144<\/code><\/p>\r\n\r\n<\/div>\r\n<h1><a id=\"_Toc519230998\"><\/a>Basic File Processing<\/h1>\r\n<p class=\"import-Normal\">While a program is running, its data is stored in random access memory (RAM) on the computer it is execution on. RAM is fast and inexpensive, but it is also volatile, which means that when the program ends, or the computer shuts down, the data in RAM disappears. To make data available the next time the computer is turned on and the program is started, it has to be written to a non-volatile storage medium, as a file. By reading and writing files, programs can save information between program runs.<\/p>\r\n<p class=\"import-Normal\">So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.<\/p>\r\n<p class=\"import-Normal\">For our purposes, we will assume that our data files are text files\u2013that is, files filled with characters. The Python programs that you write are stored as text files as are any HTML webpage files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents. Note that text files have an End-Of-Line (EOL) character to indicate each line's termination.<\/p>\r\n\r\n<h2><a id=\"_Toc519230999\"><\/a>Reading and Writing Text Files<\/h2>\r\n<p class=\"import-Normal\">In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. The following table shows the functions and methods that can be with files.<\/p>\r\n\r\n<table style=\"height: 278px\">\r\n<tbody>\r\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Function\/Method Name<\/strong><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Use<\/strong><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Explanation<\/strong><\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 59px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 167.625px\">\r\n<p class=\"import-Normal\">open<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 176.625px\">\r\n<p class=\"import-HTMLPreformatted\"><code>f1=open('workfile.txt','r')<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 835.625px\">\r\n<p class=\"import-Normal\">Open a file called <em>workfile.txt<\/em> and use it for reading. This will return a reference to a file object assigned to the variable <code>f1<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 59px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 167.625px\">\r\n<p class=\"import-Normal\">open<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 176.625px\">\r\n<p class=\"import-HTMLPreformatted\"><code>f1= open('workfile.txt','w')<\/code><\/p>\r\n<p class=\"import-Normal\"><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 835.625px\">\r\n<p class=\"import-Normal\">Open a file called <em>workfile.txt<\/em> and use it for writing. This will also return a reference to a file object assigned to the variable <code>f1<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\r\n<p class=\"import-Normal\">close<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\r\n<p class=\"import-Normal\"><code>f1.close()<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\r\n<p class=\"import-Normal\">When a file use is complete, the file must be closed. This will free up any system resources taken up by the open file.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\r\n<p class=\"import-Normal\">read<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\r\n<p class=\"import-HTMLPreformatted\"><code>data = f1.()<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\r\n<p class=\"import-Normal\">Read the entire contents of the file <code>f1<\/code> and assign it to the variable data.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 30px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 167.625px\">\r\n<p class=\"import-Normal\">write<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 176.625px\">\r\n<p class=\"import-Normal\"><code>f1.write(string)<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 835.625px\">\r\n<p class=\"import-Normal\">Write the contents of <em class=\"import-Emphasis\">string<\/em> to the file <code>f1<\/code>, returning the number of characters written.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\r\n<p class=\"import-Normal\">readline<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\r\n<p class=\"import-Normal\"><code>data = f1.readline()<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\r\n<p class=\"import-Normal\">Read a single line from the file <code>f1<\/code>; a newline character (<code>\\n<\/code>) is left at the end of the string.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p style=\"text-align: center\"><small><a id=\"_Toc519003538\"><\/a><em>Table 7: File Functions and Methods<\/em><\/small><\/p>\r\n<p class=\"import-Normal\">Python file object attributes provide information about the file and file state. The following table shows how to identify some of the object's attributes.<\/p>\r\n&nbsp;\r\n<table>\r\n<tbody>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Attribute<\/strong><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Use<\/strong><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Explanation<\/strong><\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">file.closed<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>print(\"Closed or not : \", file1.closed)<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">Returns true if <code>file1<\/code> is closed, false otherwise.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">file.mode<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>print(\"Opening mode : \", file1.mode)<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">Returns access mode with which <code>file1<\/code> was opened.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<tr class=\"TableGrid-R\">\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">file.name<\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\"><code>print(\"Name of the file: \", file1.name)<\/code><\/p>\r\n<\/td>\r\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\r\n<p class=\"import-Normal\">Returns name of <code>file1<\/code>.<\/p>\r\n<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<p style=\"text-align: center\"><em><small>Table 8: File Object Attributes<\/small><\/em><\/p>\r\n<p class=\"import-Normal\">The statement<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file1 = open('myfile.txt', 'r')<\/code><\/p>\r\n<p class=\"import-Normal\">creates and returns a file object in the variable named <code>file1<\/code>. The first argument to open is the name of the file, and the second argument is a mode (in this example the mode is to read the file). This statement will attempt to read the content of the text file named <code>myfile.txt<\/code>. If the file does not exist or the user of the program does not have adequate permissions to open the file, the <code>open<\/code> function will raise an exception.<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>try:<\/code>\r\n<p style=\"padding-left: 30px\"><code>file1 = open('myfile.txt', 'r')<\/code><\/p>\r\n<code>except:<\/code>\r\n<p style=\"padding-left: 30px\"><code>print(\u201cERROR: unable to open or locate the file\u201d)<\/code><\/p>\r\n<code># Do other kinds of processing here...<\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Similar to handling an error of invalid user input we need to use the <code>try-except-else<\/code> block to handle trying to read from a file which does not exist The following is an example:<\/p>\r\n<p class=\"import-Normal\">The statement<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2 = open('myfile.txt', 'w')<\/code><\/p>\r\n<p class=\"import-Normal\">creates and returns a file object in the variable named <code>file2<\/code> which will write data to the text file named <code>myfile.txt<\/code>. If the file does not exist, the function creates the file on disk; no exceptions are raised when writing to a file. If a file by that name currently exists, new data will replace the current data stored in the file. This means any pre-existing data in the file will be lost.<\/p>\r\n<p class=\"import-Normal\">Once you have a file object capable of writing (opened with 'w') you can save data to the file associated with that file object using the write method. For a file object named <code>file2<\/code>, the statement<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data')<\/code><\/p>\r\n<p class=\"import-Normal\">stores the string 'data' to the file. The three statements<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data')<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('compute')<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('process')<\/code><\/p>\r\n<p class=\"import-Normal\">writes the text <code>'datacomputeprocess'<\/code> to the file. If our intention is to retrieve the three separate original strings, we must add delimiters to separate the pieces of data. Newline characters serve as good delimiters:<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data\\n')<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('compute\\n')<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('process\\n')<\/code><\/p>\r\n<p class=\"import-Normal\">This places each word on its own line in the text file. The advantage of storing each piece of data on its own line of text is that it makes it easier to read the data from the file with a <code>for<\/code> statement. If <code>file2<\/code> is a file object created for reading, the following code:<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>for line in file2:<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>print(line.strip())<\/code><\/p>\r\n<p class=\"import-Normal\">reads in each line of text from the file and prints it out. The variable <code>line<\/code> is a string, and we use the <code>strip<\/code> method to remove the trailing newline (<code>'\\n'<\/code>) character.<\/p>\r\n<p class=\"import-Normal\">We also can read the contents of the entire file into a single string using the file object\u2019s read method:<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>contents = file2.read()<\/code><\/p>\r\n<p class=\"import-Normal\">Given the text file from above, the code<\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>in = open('compterms.txt', 'r')<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>str = in.read()<\/code><\/p>\r\n<p class=\"import-Normal\">assigns to <code>str<\/code> the string <code>'data\\ncompute\\nprocess\\n'<\/code>.<\/p>\r\n<p class=\"import-Normal\">The <code>open<\/code> method opens a file for reading or writing, and the <code>read<\/code>, <code>write<\/code>, and other such methods enable the program to interact with the file. When the executing program is finished with its file processing it must call the <code>close<\/code> method to close the file properly. Failure to close a file can have serious consequences when writing to a file, as data meant to be saved could be lost. Every call to the open function should have a corresponding call to the file object\u2019s <code>close<\/code> method.<\/p>\r\n\r\n<h2 class=\"import-Normal\"><span class=\"import-Heading3Char\">Practice<\/span> - Following are two simple programs designed to write data to a file and then read and print each line of a file. Try entering, saving and running the following programs (<code>writeFile.py<\/code> and <code>readFile.py<\/code>).<\/h2>\r\n<div class=\"textbox\"><code>file1 = open(\"compterms.txt\", 'w') #Create a file to write to<\/code>\r\n<code># write data to the opened file<\/code>\r\n<code>file1.write('data\\n')<\/code>\r\n<code>file1.write('compute\\n')<\/code>\r\n<code>file1.write('process\\n')<\/code>\r\n<code>file1.write('file format\\n')<\/code>\r\n<code>file1.write('gigabyte\\n')<\/code>\r\n<code>file1.close() # Close the file after processing data<\/code><\/div>\r\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 49: writeFile.py<\/em><\/p>\r\n<p class=\"import-Normal\">Figure 50: readFile.py<\/p>\r\n\r\n<div class=\"textbox\"><span class=\"import-Normal\">try:\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">file1 = open('compterms.txt','r') # try to find &amp; open the file<\/code>\r\n<code class=\"import-Normal\">except:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code>\r\n<code class=\"import-Normal\">else:<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 60px\">print(line.strip()) # Remove trailing newline character and print the line<\/code>\r\n<code class=\"import-Normal\" style=\"padding-left: 30px\">file1.close() # Close the file after processing data\r\n<\/code><\/span><\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">This is the output after running this program:<\/p>\r\n\r\n<div class=\"textbox\">RESTART: C:\/Users\/lh166266.UALBANY\/Code\/readFile.py\r\n<code style=\"color: #0000ff\">data<\/code>\r\n<code style=\"color: #0000ff\">compute<\/code>\r\n<code style=\"color: #0000ff\">process<\/code>\r\n<code style=\"color: #0000ff\">file format<\/code>\r\n<code style=\"color: #0000ff\">gigabyte<\/code>\r\n&gt;&gt;&gt;<\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">We can also read and process each line of data in a file by using the <code>readline()<\/code> method. Try entering, saving and running the following programs <code>(readFile2.py)<\/code>. The output is the same.<\/p>\r\n\r\n<div class=\"textbox\">\r\n\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">file1 = open('compterms.txt','r') # try to find &amp; open the file<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">line = file1.readline() # Read the first line<\/code>\r\n<code style=\"padding-left: 30px\">while line: # Enter the loop as long as there is a line of<\/code>\r\n<code>data to read<\/code>\r\n<code style=\"padding-left: 30px\">print(line.strip()) # Remove trailing newline character and print the line<\/code>\r\n<code style=\"padding-left: 30px\">line = file1.readline() # Read the next line<\/code>\r\n<code>file1.close() # Close the file after processing data<\/code>\r\n\r\n<\/div>\r\n&nbsp;\r\n<h2><a id=\"_Toc519231001\"><\/a>Processing \u201cBig Data\u201d<\/h2>\r\n<p class=\"import-Normal\">Big data is large, and often times complex, data sets that need to be processed into useful information. Python has emerged over the past few years as a leader in data science programming including the analysis and visualization of large data sets.<\/p>\r\n<p class=\"import-Normal\">Data sets grow rapidly - in part because they are increasingly gathered by cheap and numerous information-sensing internet of things devices such as mobile devices, aerial (remote sensing), software logs, cameras, microphones, radio-frequency identification (RFID) readers and wireless sensor networks. The world's technological per-capita capacity to store information has roughly doubled every 40 months since the 1980s; as of 2012, every day 2.5 exabytes (2.5\u00d71018) of data are generated. Based on an IDC (International Data Corporation) report prediction, the global data volume will grow exponentially from 4.4 zettabytes to 44 zettabytes between 2013 and 2020. By 2025, IDC predicts there will be 163 zettabytes of data.<sup class=\"import-FootnoteReference\">[footnote]Wikipedia contributors. \"Big data.\" Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 4 Jul. 2018. Web. 12 Jul. 2018.[\/footnote]<\/sup><\/p>\r\n\r\n\r\n[caption id=\"\" align=\"alignright\" width=\"267\"]<img src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161443\/image49.jpg\" alt=\"image\" width=\"267\" height=\"189\" \/> Figure 51: \u201cData Information\u201d(www.maxpixel.net\/Circle-Know-Arrangement-Data-Information-Learn-229113)\u00a0is licensed under <a href=\"https:\/\/creativecommons.org\/share-your-work\/public-domain\/cc0\/\">CC-BY 0<\/a>[\/caption]\r\n<p class=\"import-Normal\">An example of a successful business that uses python for collecting and analyzing data is ForecastWatch. ForecastWatch.com is in the business of rating the accuracy of weather reports from companies such as Accuweather, MyForecast.com, and The Weather Channel. Over 36,000 weather forecasts are collected every day for over 800 U.S. cities, and later compared with actual climatological data. These comparisons are used by meteorologists to improve their weather forecasts, and to compare their forecasts with others. They are also used by consumers to better understand the probable accuracy of a forecast.<sup class=\"import-FootnoteReference\">[footnote]Python Software Foundation. Python Success Stories, https:\/\/www.python.org\/about\/success\/forecastwatch\/. Accessed July 12, 2018[\/footnote]<\/sup><\/p>\r\n<p class=\"import-Normal\">We will use real data from open source data sets (that is saved as text files) for programming practice.<\/p>\r\n\r\n<h2><a id=\"_Toc519231002\"><\/a>Practice<\/h2>\r\n<p class=\"import-Normal\"><strong>Problem Statement<\/strong>: Using the text file, <code>NYScoastalFlooding.txt<\/code>, identify each of the New York State counties (zones) effected by coastal flooding during the month of August within the dataset provided.<\/p>\r\n<p class=\"import-Normal\">The first step in finding a solution for this problem is to review and understand the format of the data set provided. Open the text in a text editor and note the field headings in the first line of the file. The following is a small sample from the <code>NYScoastalFlooding.txt<\/code> file.<\/p>\r\n\r\n<div class=\"textbox\"><code>YEAR, MONTH_NAME, EVENT_TYPE, CZ_TYPE,CZ_FIPS, CZ_NAME<\/code>\r\n<code>2017, March, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code>\r\n<code>2017, March, Coastal Flood, Z, 179, SOUTHERN NASSAU<\/code>\r\n<code>2017, March, Coastal Flood, Z, 71, SOUTHERN WESTCHESTER<\/code>\r\n<code>2017, March, Coastal Flood, Z, 81, SOUTHEAST SUFFOLK<\/code>\r\n<code>2017, October, Coastal Flood, Z, 3, MONROE<\/code>\r\n<code>2017, October, Coastal Flood, Z, 5, NORTHERN CAYUGA<\/code>\r\n<code>2017, October, Coastal Flood, Z, 4, WAYNE<\/code>\r\n<code>2017, October, Coastal Flood, Z, 6, OSWEGO<\/code>\r\n<code>2017, January, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code>\r\n<code>2017, October, Coastal Flood, Z, 1, NIAGARA<\/code>\r\n<code>2017, January, Coastal Flood, Z, 179, SOUTHERN NASSAU<\/code><\/div>\r\n<p class=\"import-Normal\">We see that the data set has six fields:<\/p>\r\n\r\n<ol>\r\n \t<li>year: Four digit year for the event in this record<\/li>\r\n \t<li>month_name: Name of the month for the event in this record (spelled out; not abbreviated)<\/li>\r\n \t<li>event_type spelled out; not abbreviated<\/li>\r\n \t<li>cz_type: Indicates whether the event happened in a (C) county\/parish, (Z) zone or (M) marine<\/li>\r\n \t<li>cz_fips: The county FIPS number is a unique number assigned to the county by the National Institute for Standards and Technology (NIST) or NWS Forecast Zone Number<\/li>\r\n \t<li>cz_name: County\/Parish, Zone or Marine Name assigned to the county FIPS number or NWS Forecast Zone<\/li>\r\n<\/ol>\r\n<p class=\"import-Normal\">We also notice that all but the first field on each line has a blank space before it (this is important!).<\/p>\r\nWe will break this problem into smaller pieces. Let us start with a program that reads each of the records and keeps a count of the number of records in the file (dataRecordNumb.py). This program is a modification of our readFile.py program.\r\n<div class=\"textbox\">\r\n\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">file1 = open('NYScoastalFlooding.txt ','r') # try to find &amp; open the file<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">count = 0 # Initialize recount cout to zero<\/code>\r\n<code style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code>\r\n<code style=\"padding-left: 60px\">print(line.strip()) # Print the record<\/code>\r\n<code style=\"padding-left: 60px\">count = count + 1 # increment record counter<\/code>\r\n<code style=\"padding-left: 30px\">print(\"There are\",count,\"data records in this file\")<\/code>\r\n<code style=\"padding-left: 30px\">file1.close() # Close the file after processing data<\/code>\r\n\r\n<\/div>\r\n<p class=\"import-Normal\">The last line of the output from running this program:<\/p>\r\n\r\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/dataRecordNumb.py<\/code>\r\n<code style=\"color: #0000ff\">There are 61 data records in this file<\/code>\r\n<code>&gt;&gt;&gt;<\/code><\/div>\r\n&nbsp;\r\n<p class=\"import-Normal\">Recall from Unit 2 when we used the <code>split()<\/code> method to identify each individual word in a sentence. What the method does is split or breakup a string and add the data to a list of separate \u2018chunks\u2019 using a defined separator. So if this line is read<\/p>\r\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>2017, January, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code><\/p>\r\n<p class=\"import-Normal\">and we split the line into individual fields we could identify those records effected by coastal flooding during the month of August.<\/p>\r\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>fields = line.split(\u2018,\u2019)<\/code><\/p>\r\n<p class=\"import-Normal\">If we now print fields we have a list of all the fields which we can now access.<\/p>\r\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>&gt;&gt;&gt; print(fields)<\/code><\/p>\r\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>['2017', ' January', ' Coastal Flood', ' Z', ' 79', ' NORTHEAST SUFFOLK']<\/code><\/p>\r\n<p class=\"import-Normal\">Notice the extra blank space before the string \u201cJanuary\u201d in the list <code>fields<\/code>. When trying to identify those records with the string \u201cAugust\u201d the extra space must be dealt with!<\/p>\r\nLet us complete the second program to solve the problem of identifying (and print) each of the New York State counties (zones) effected by coastal flooding during the month of August (<code>NYScountiesAug.py<\/code>).\r\n<div class=\"textbox\">\r\n\r\n<code># identify each of the New York State counties (zones) effected by coastal flooding during the month of August<\/code>\r\n<code>print(\"The following are the NYS counties (zones) effected by coastal flooding during the month of August:\")<\/code>\r\n<code>try:<\/code>\r\n<code style=\"padding-left: 30px\">file1 = open('NYScoastalFlooding.txt ','r') # try to find &amp; open the file<\/code>\r\n<code>except:<\/code>\r\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code>\r\n<code>else:<\/code>\r\n<code style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code>\r\n<code style=\"padding-left: 60px\">fields = line.split(\",\") # split each line into a list of 'fields'<\/code>\r\n<code style=\"padding-left: 60px\">if fields[1] == \" August\": # check if the 2nd field is August<\/code>\r\n<code style=\"padding-left: 90px\">county = fields[5] # identify the county from the 6th field<\/code>\r\n<code style=\"padding-left: 90px\">print(county.strip()) # Print the record<\/code>\r\n<code style=\"padding-left: 30px\">file1.close() # Close the file after processing data<\/code>\r\n\r\n<\/div>\r\nThe output from running this program:\r\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/NYScountiesAug.py<\/code>\r\n<code style=\"color: #0000ff\">The following are the NYS counties (zones) <\/code><code>effected<\/code><code style=\"color: #0000ff\"> by coastal flooding during the month of August:<\/code>\r\n<code style=\"color: #0000ff\">OSWEGO<\/code>\r\n<code style=\"color: #0000ff\">NIAGARA<\/code>\r\n<code style=\"color: #0000ff\">NORTHERN CAYUGA<\/code>\r\n<code style=\"color: #0000ff\">JEFFERSON<\/code>\r\n<code style=\"color: #0000ff\">ORLEANS<\/code>\r\n<code style=\"color: #0000ff\">MONROE<\/code>\r\n<code style=\"color: #0000ff\">WAYNE<\/code>\r\n&gt;&gt;&gt;<\/div>\r\n<p class=\"import-Normal\">To test if the program correctly identified all records effected by coastal flooding during the month of August you would need to manually go through each of the 61 records and flag the records that should be found and printed (or use an app such as Excel to do a sort and count for you).<\/p>\r\n<p class=\"import-Normal\">The actual data set I downloaded had a total of 56,921 records and 51 different fields (a lot more data than what we just worked with!). A professional data scientist would also test her program using a subset of the large data set until she could be satisfied that the program was running correctly and producing the correct results.<\/p>\r\n\r\n<h1><a id=\"_Toc519231003\"><\/a>Unit Summary<\/h1>\r\n<p class=\"import-Normal\">TBD<\/p>\r\n\r\n<ul>\r\n \t<li>Read and write programs using the Python IF and IF\/ELIF\/ELSE statements to implement a simple decision structures.<\/li>\r\n \t<li>Write simple exception handling code to catch simple Python run-time errors.<\/li>\r\n \t<li>Read and write programs using the Python FOR and WHILE statements to implement a simple loop structures.<\/li>\r\n \t<li>Construct and implement algorithms that use decision and loop structures.<\/li>\r\n \t<li>Apply basic file processing concepts and techniques for reading and writing text files in Python.<\/li>\r\n<\/ul>\r\n<h1><a id=\"_Toc519231004\"><\/a>Practice Problems<\/h1>\r\n<ol>\r\n \t<li>Write a program to accept a number from the user and print whether it is positive or negative.<\/li>\r\n \t<li>Accept three numbers from the user and print the greatest number.<\/li>\r\n \t<li>Write a program that accepts a number in the range from 1 to 7 from the user and generates and displays the name of the weekday.<\/li>\r\n \t<li>Write a program to input 5 numbers from the user and calculates and displays their sum and average.<\/li>\r\n \t<li>Write a program that accepts an integer number and indicates whether it is negative, zero, or positive. Force the user to enter only valid data (repeatedly ask the user to enter only an integer number)<\/li>\r\n \t<li>Provide the exact sequence of integers specified by each of the following range expressions.\r\n<ol type=\"a\">\r\n \t<li>range(5)<\/li>\r\n \t<li>range(5, 10)<\/li>\r\n \t<li>range(5, 20, 3)<\/li>\r\n \t<li>range(20, 5, -1)<\/li>\r\n \t<li>range(20, 5, -3)<\/li>\r\n \t<li>range(10, 5)<\/li>\r\n \t<li>range(0)<\/li>\r\n \t<li>range(10, 101, 10)<\/li>\r\n \t<li>range(10, -1, -1)<\/li>\r\n \t<li>range(-3, 4)<\/li>\r\n \t<li>range(0, 10, 1)<\/li>\r\n<\/ol>\r\n<\/li>\r\n \t<li>Write a program to print a pattern like a right angle triangle with numbers where each number will repeat in a row. The pattern is as follows:\r\n1\r\n22\r\n333\r\n4444\r\n55555<\/li>\r\n \t<li>Write a program to print a pattern like a pyramid with numbers where each number will repeat in a row. The pattern is as follows:\r\n<img class=\"alignnone size-full wp-image-117\" style=\"text-align: initial;font-size: 1em\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161444\/Screen-Shot-2018-07-18-at-3.28.16-PM.png\" alt=\"\" width=\"156\" height=\"115\" \/><\/li>\r\n \t<li>Find a poem you like and save it as a text file named poem.txt. Write a program that counts the number of lines in your program. Print out the line count and each individual line in the program (no extra blank lines!)<\/li>\r\n \t<li>Write a program that stores the first 100 integers to a text file named numbers.txt. Each number should appear on a line all by itself.<\/li>\r\n \t<li>Write a program to find the longest word in a text file.<\/li>\r\n<\/ol>\r\n<div id=\"sdfootnote21sym\">\u2026<\/div>\r\n<div id=\"sdfootnote22sym\">\u2026<\/div>","rendered":"<div class=\"unit-4:-control-structures:-making-decisions-and-looping-in-computing.-data-and-information-processing-in-python.\">\n<h1><a id=\"_Toc519230974\"><\/a>Learning Objectives<\/h1>\n<ul>\n<li>Read and write programs using the Python IF and IF\/ELIF\/ELSE statements to implement a simple decision structures.<\/li>\n<li>Write simple exception handling code to catch simple Python run-time errors.<\/li>\n<li>Read and write programs using the Python FOR and WHILE statements to implement a simple loop structures.<\/li>\n<li>Construct and implement algorithms that use decision and loop structures.<\/li>\n<li>Apply basic file processing concepts and techniques for reading and writing text files in Python.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<ul>\n<li><a href=\"#_Toc519230975\">Boolean Expressions<\/a><\/li>\n<li><a href=\"#_Toc519230976\">Logical Operators<\/a><\/li>\n<li><a href=\"#_Toc519230977\">Conditional Execution<\/a><\/li>\n<\/ul>\n<\/div>\n<div class=\"unit-4:-control-structures:-making-decisions-and-looping-in-computing.-data-and-information-processing-in-python.\">\n<h1><a id=\"_Toc519230975\"><\/a>Boolean Expressions<\/h1>\n<p class=\"import-Normal\">Arithmetic expressions evaluate to numeric values; a Boolean expression may have only one of two possible values: <strong>false<\/strong> or <strong>true<\/strong>. While on the surface Boolean expressions may appear very limited compared to numeric expressions, they are essential for building more interesting and useful programs.<\/p>\n<p>The simplest Boolean expressions in Python are <code>True<\/code> and <code>False<\/code>. In the Python interactive shell we see:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; True<\/code><br \/>\n<code>True<\/code><br \/>\n<code>&gt;&gt;&gt; False<\/code><br \/>\n<code>False<\/code><br \/>\n<code>&gt;&gt;&gt; type(True)<\/code><br \/>\n<code>&lt;class 'bool'&gt;<\/code><br \/>\n<code>&gt;&gt;&gt; type(False)<\/code><br \/>\n<code>&lt;class 'bool'&gt;<\/code><\/div>\n<p class=\"import-Normal\">We see that <code>bool<\/code> is the name of the class representing Python\u2019s Boolean expressions. The following code <code>(booleanVars.py)<\/code> is a simple program that shows how Boolean variables can be used.<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code># Assign some Boolean variables<\/code><br \/>\n<code>a = True<\/code><br \/>\n<code>b = False<\/code><br \/>\n<code>print('a =', a, ' b =', b)<\/code><br \/>\n<code># Reassign a<\/code><br \/>\n<code>a = False<\/code><br \/>\n<code>print('a =', a, ' b =', b)<\/code><\/p>\n<\/div>\n<p>The results of running this program are shown below:<\/p>\n<div class=\"textbox\"><code>a = True b = False<\/code><br \/>\n<code>a = False b = False<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">A Boolean variable is also a Boolean expression as we saw in Unit 2. An expression comparing numeric expressions for equality or inequality is also a Boolean expression. The simplest kinds of Boolean expressions use relational operators (or comparison operators) to compare two expressions. Table 6 lists the relational operators available in Python.<\/p>\n<table>\n<tbody>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Expression<\/strong><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Meaning<\/strong><\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x == y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>equals<\/em> y (mathematical equality, not assignment); otherwise, false<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x &lt; y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>less than<\/em> y; otherwise, false<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x &lt;= y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>less than and equal to y<\/em>; otherwise, false<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x &gt; y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>greater than<\/em> y; otherwise, false<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x &gt;= y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>greater than and equal to y<\/em>; otherwise, false<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 21.6pt\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>x != y<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">True if x <em>not equal to<\/em> y; otherwise, false<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: center\"><small><a id=\"_Toc519003537\"><\/a>Table 6: Python Relationa\/Comparisonl Operators<\/small><\/p>\n<p class=\"import-Normal\">In the Python interactive shell we see some examples of Boolean expressions:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; 10 &lt; 20<\/code><br \/>\n<code>True<\/code><br \/>\n<code>&gt;&gt;&gt; 10 &gt;= 20<\/code><br \/>\n<code>False<\/code><br \/>\n<code>&gt;&gt;&gt; x = 19<\/code><br \/>\n<code>&gt;&gt;&gt; y = 29<\/code><br \/>\n<code>&gt;&gt;&gt; x &lt; 100<\/code><br \/>\n<code>True&gt;&gt;&gt; x != y<\/code><br \/>\n<code>True<\/code><\/div>\n<p class=\"import-Normal\">An expression like <code>10 &lt; 20<\/code> is legal but of little use, since <code>10 &lt; 20<\/code> is always true; the expression <code>True<\/code> is equivalent, simpler, and less likely to confuse human readers. Since variables can change their values during a program\u2019s execution (and often do!), Boolean expressions are most useful when their truth values depend on the values of one or more variables.<\/p>\n<p class=\"import-Normal\">The relational\/comparison operators are binary operators and are all left associative. They all have a lower precedence than any of the arithmetic operators; therefore, Python evaluates the expression<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>x + 2 &lt; y \/ 10<\/code><\/p>\n<p class=\"import-Normal\">as if parentheses were placed as so:<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>(x + 2) &lt; (y \/ 10)<\/code><\/p>\n<h1><a id=\"_Toc519230976\"><\/a>Logical operators<\/h1>\n<p class=\"import-Normal\">There are three logical operators: <code>and<\/code>, <code>or<\/code>, and <code>not<\/code>. The semantics (meaning) of these operators is similar to their meaning in English. For example, <code>x &gt; 0<\/code> and <code>x &lt; 10<\/code> is true only if <code>x<\/code> is greater than 0 and less than 10.<\/p>\n<p class=\"import-Normal\"><code>n%2 == 0 or n%3 == 0<\/code> is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.<\/p>\n<p class=\"import-Normal\">Finally, the <code>not<\/code> operator negates a Boolean expression, so <code>not (x &gt; y)<\/code> is true if <code>x &gt; y<\/code> is false, that is, if <code>x<\/code> is less than or equal to <code>y<\/code>.<\/p>\n<p>Strictly speaking, the operands of the logical operators should be Boolean expressions, but Python is not very strict. Any nonzero number is interpreted as <code>True<\/code>:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; 42 and True<\/code><br \/>\n<code>True<\/code><\/div>\n<p class=\"import-Normal\">This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).<\/p>\n<h1><a id=\"_Toc519230977\"><\/a>Conditional execution<\/h1>\n<p>In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the <code style=\"font-weight: bold\">if<\/code> statement:<\/p>\n<div class=\"textbox\"><code>if x &gt; 0:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x is positive')<\/code><\/div>\n<div style=\"width: 252px\" class=\"wp-caption alignright\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161431\/image42.png\" alt=\"image\" width=\"242\" height=\"245\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 41: Simple IF Conditional Flowchart<\/p>\n<\/div>\n<p class=\"import-Normal\">The Boolean expression after <code>if<\/code> is called the condition. If it is true, the indented statement runs. If not, nothing happens. See the corresponding flowchart in figure 42.<\/p>\n<p class=\"import-Normal\"><code>if<\/code> statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.<\/p>\n<p class=\"import-Normal\">There is no limit on the number of statements that can appear in the body, but there has to be at least one.<\/p>\n<hr \/>\n<p class=\"import-Normal\">A second form of the if statement is \u201calternative execution\u201d (<code style=\"font-weight: bold\">if-else<\/code>), in which there are two possibilities and the condition determines which one runs. The syntax looks like this:<\/p>\n<div class=\"textbox\" style=\"padding-left: 30px\">\n<p><code>if x % 2 == 0:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x is even')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x is odd')<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<div style=\"width: 537px\" class=\"wp-caption alignright\"><img loading=\"lazy\" decoding=\"async\" class=\"\" style=\"font-size: 1em\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161432\/image43.png\" alt=\"image\" width=\"527\" height=\"286\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 42: Alternative Execution Conditional Flowchart<\/p>\n<\/div>\n<p class=\"import-Normal\"><span class=\"import-y0nh1b\">Modulus<\/span><span class=\"import-y0nh1b\"> or remainder <\/span><span class=\"import-y0nh1b\">operator<\/span><span class=\"import-y0nh1b\">, \u2018<\/span><code><span class=\"import-y0nh1b\">%<\/span><\/code><span class=\"import-y0nh1b\">\u2019, returns the remainder of two numbers. So in this example, i<\/span>f the remainder when <code>x<\/code> is divided by 2 is 0, then we know that <code>x<\/code> is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution. See the corresponding flowchart in figure 42.<\/p>\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code><span class=\"import-y0nh1b\">if <\/span><\/code><span lang=\"en\" xml:lang=\"en\">statement is used to check a condition: <\/span><em lang=\"en\" xml:lang=\"en\">if<\/em><span lang=\"en\" xml:lang=\"en\"> the condition is true, we run a <\/span><span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> of statements (called the <\/span><em lang=\"en\" xml:lang=\"en\">if-block<\/em><span lang=\"en\" xml:lang=\"en\">), <\/span><em lang=\"en\" xml:lang=\"en\">else<\/em><span lang=\"en\" xml:lang=\"en\"> we process another <\/span><span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> of statements (called the <\/span><em lang=\"en\" xml:lang=\"en\">else-block<\/em><span lang=\"en\" xml:lang=\"en\">). The <\/span><em lang=\"en\" xml:lang=\"en\">else<\/em><span lang=\"en\" xml:lang=\"en\"> clause is optional. In our earlier examples we only had one statement in a block. <\/span>Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional (<code style=\"font-weight: bold\">if-elif-else<\/code>). <span lang=\"en\" xml:lang=\"en\">The following program, <\/span><code>ifElse.py<\/code><span lang=\"en\" xml:lang=\"en\">, show<\/span><span lang=\"en\" xml:lang=\"en\">s<\/span><span lang=\"en\" xml:lang=\"en\"> us multiple statements in each block.<\/span><\/p>\n<div class=\"textbox\">\n<p><code>number = 23<\/code><br \/>\n<code>guess = int(input('Enter an integer : '))<\/code><\/p>\n<p><code>if guess == number:<\/code><br \/>\n<code style=\"padding-left: 30px\"># New block starts here<\/code><br \/>\n<code style=\"padding-left: 30px\">print('Congratulations, you guessed it.')<\/code><br \/>\n<code style=\"padding-left: 30px\">print('(but you do not win any prizes!)')<\/code><br \/>\n<code style=\"padding-left: 30px\"># New block ends here<\/code><br \/>\n<code>elif guess &lt; number:<\/code><br \/>\n<code style=\"padding-left: 30px\"># Another block<\/code><br \/>\n<code style=\"padding-left: 30px\">print('No, it is a little higher than that')<\/code><br \/>\n<code style=\"padding-left: 30px\"># You can do whatever you want in a block ...<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('No, it is a little lower than that')<\/code><br \/>\n<code style=\"padding-left: 30px\"># you must have guessed &gt; number to reach here<\/code><\/p>\n<p><code>print('Done')<\/code><br \/>\n<code># This last statement is always executed,<\/code><br \/>\n<code># after the if statement is executed.<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">In this program, we take guesses from the user and check if it is the number that we have. We set the variable <code>number<\/code> to any integer we want, say 23. Then, we take the user&#8217;s guess using the <code>input()<\/code> function. We then convert this string to an integer using <code>int<\/code> and then store it in the variable <code>guess<\/code>.<\/p>\n<p class=\"import-Normal\">Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that.<\/p>\n<p class=\"import-Normal\">After Python has finished executing the complete <code>if<\/code> statement along with the associated <code>elif<\/code> and <code>else<\/code> clauses, it moves on to the next statement in the block containing the <code>if<\/code> statement. In this case, it is the main block (where execution of the program starts), and the next statement is the <code>print('Done')<\/code> statement. After this, Python sees the end of the program and simply finishes up.<\/p>\n<p>The following code is another example of a conditional statement with more than two branches:<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>if x &lt; y:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is less than y')<\/code><br \/>\n<code class=\"import-Normal\">elif x &gt; y:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is greater than y')<\/code><br \/>\n<code class=\"import-Normal\">else:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x and y are equal')<\/code><\/p>\n<\/div>\n<div style=\"width: 625px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161434\/image44.png\" alt=\"image\" width=\"615\" height=\"385\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 43: Two or More Branches Conditional Flowchart<\/p>\n<\/div>\n<p class=\"import-Normal\"><code>elif<\/code> is an abbreviation of \u201celse if\u201d. Again, exactly one branch will run. There is no limit on the number of <code>elif<\/code> statements. See the corresponding flowchart in figure 43. If there is an <code>else<\/code> clause, it has to be at the end, but there doesn\u2019t have to be one. See the following example:<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>if choice == 'a':<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_a()<\/code><br \/>\n<code class=\"import-Normal\">elif choice == 'b':<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_b()<\/code><br \/>\n<code class=\"import-Normal\">elif choice == 'c':<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">draw_c()<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first<code> true<\/code> branch runs. It is good practice to include the <code>else<\/code> clause as the final branch in the <code style=\"font-weight: bold\">if-elif-else<\/code> statement.<\/p>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230978\"><\/a><span class=\"import-Heading3Char\">Practic<\/span><span class=\"import-Heading3Char\">e <\/span><span class=\"import-Heading3Char\">\u2013<\/span> Write a program to accept a test score as input and print out the corresponding letter grade. First examine the flowchart (figure 44) of the problem we are solving. Then, using the Python editor, enter the following code (save as <code>testGrade.py<\/code> ):<\/h2>\n<div style=\"width: 562px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161436\/image45.png\" alt=\"image\" width=\"552\" height=\"395\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 44: if-elif-else Conditional Flowchart<\/p>\n<\/div>\n<div class=\"textbox\">\n<p><code>#accept a test score as input and print out the corresponding letter grade<\/code><br \/>\n<code>testScore = float(input(\"Enter a test score from 0 to 100: \"))<\/code><br \/>\n<code># conditional statement to determine and print the test letter grade<\/code><br \/>\n<code>if testScore &gt;= 90:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is A\")<\/code><br \/>\n<code>elif testScore &gt;= 80:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is B\")<\/code><br \/>\n<code>elif testScore &gt;= 70:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is C\")<\/code><br \/>\n<code>elif testScore &gt;= 60:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is D\")<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is F\")<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">Output:<\/p>\n<p class=\"import-Normal\"><img decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161438\/image46.png\" alt=\"image\" width=\"488.750971128609px\" height=\"210.6px\" \/><\/p>\n<p class=\"import-Normal\">Let us examine how this program works.<\/p>\n<table>\n<tbody>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>testScore = float(input(\"Enter a test score from 0 to 100: \"))<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">Accept a numeric test grade from the user as a string and convert the number to a floating point values. Save this value in a variable named <code>\u201ctestScore\u201d<\/code>.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>if testScore &gt;= 90:<\/code><br \/>\n<code><span style=\"font-family: inherit;font-size: inherit\">\u00a0 \u00a0 print(\"your grade is A\")<\/span><\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The first branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 90) is <code>true<\/code> then we print the letter grade \u201cA\u201d using the <code>print<\/code> function and end the program. If the condition is <code>false<\/code>, the program continues to the next branch (the first <code>elif<\/code> condition).<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>elif testScore &gt;= 80:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is B\")<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The second branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 80) is <code>true<\/code> then we print the letter grade \u201cB\u201d using the <code>print<\/code> function and end the program. If the condition is <code>false,<\/code> the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 90 .This was determined in the first branch (the previous <code>if<\/code> condition). Therefore we know that the score MUST be less than 90.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>elif testScore &gt;= 70:<\/code><br \/>\n<code><span style=\"font-family: inherit;font-size: inherit\">\u00a0 \u00a0 print(\"your grade is C\")<\/span><\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The third branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 70) is <code>true<\/code> then we print the letter grade \u201cC\u201d and end the program. If the condition is <code>false<\/code>, the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 80 . Therefore we know that the score MUST be less than 80.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>elif testScore &gt;= 60:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is D\")<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The fourth branch of this chained conditional is executed. If this condition (the test score is greater than or equal to 60) is <code>true<\/code> then we print the letter grade \u201cD\u201d and end the program. If the condition is <code>false<\/code>, the program continues to the next branch.<br style=\"clear: both\" \/>Note that this statement will not be executed if the test score is above a 70 . Therefore we know that the score MUST be less than 70.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"your grade is F\")<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The \u201c<code>else<\/code>\u201d is the final branch of the chained conditional statement. In order to execute this branch ALL previous conditions must have been evaluated to \u201c<code>false<\/code>\u201d. Note that this statement will not be executed if the test score is above a 60.<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"import-Normal\">One conditional can also be nested within another called <strong>nested conditionals<\/strong>. Earlier in this section we saw the following example using a chained conditional (<code style=\"font-weight: bold\">if-elif-else<\/code>).<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>if x &lt; y:<\/code><\/p>\n<p><code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is less than y')<\/code><br \/>\n<code class=\"import-Normal\">elif x &gt; y:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is greater than y')<\/code><br \/>\n<code class=\"import-Normal\">else:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x and y are equal')<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">We could have just as easily written this code using nested conditionals like this:<\/p>\n<div>\n<div class=\"textbox\">\n<p><code>if x == y:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x and y are equal')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">if x &lt; y:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('x is less than y')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x is greater than y')<\/code><\/p>\n<\/div>\n<\/div>\n<p class=\"import-Normal\">The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.<\/p>\n<p class=\"import-Normal\">Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.<\/p>\n<p>Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:<\/p>\n<div class=\"textbox\">\n<p><code>if 0 &lt; x:<\/code><br \/>\n<code style=\"padding-left: 30px\">if x &lt; 10:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('x is a positive single-digit number.')<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator:<\/p>\n<div class=\"textbox\">\n<p><code>if 0 &lt; x and x &lt; 10:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('x is a positive single-digit number.')<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">For this kind of condition, Python provides even a more concise option:<\/p>\n<div class=\"textbox\"><code class=\"import-Normal\">if 0 &lt; x &lt; 10:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('x is a positive single-digit number.')<\/code><\/div>\n<h1 class=\"import-Normal\">Exception Handling<\/h1>\n<p class=\"import-Normal\">In our programming experience so far we have encountered several kinds of programming run-time exceptions, such as division by zero, attempting to read a variable that has not been defined, and attempting to convert a non-number to an integer. We have seen these and other run-time exceptions immediately terminate a running program.<\/p>\n<p class=\"import-Normal\">Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero).<\/p>\n<p class=\"import-Normal\">Python provides a standard mechanism called exception handling that allows programmers to deal with these kinds of run-time exceptions and many more. Rather than always terminating the program\u2019s execution (this is called a program \u201ccrash\u201d), an executing program can detect the problem when it arises and possibly execute code to correct the issue it in some way.<\/p>\n<p class=\"import-Normal\">Exceptions occur when <em>exceptional situations<\/em> occur in your program. Similarly, what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error.<\/p>\n<h2><a id=\"_Toc519230980\"><\/a>Errors<\/h2>\n<p class=\"import-Normal\">Consider the simple <code>print<\/code> function call. What if we misspell <code>print<\/code> as <code>Print<\/code>? Note the capitalization. In this case, Python raises a syntax error. The following output appears in the Python shell. Observe that a <code>NameError<\/code> is raised and also the location of the error detected is printed. This is what an error handler for this error does.<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>&gt;&gt;&gt;Print(\"hello there!\")<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#0&gt;\", line 1, in &lt;module&gt; <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 Print(\"hello there!\")<\/code><br \/>\n<code style=\"color: #ff0000\">NameError: name 'Print' is not defined<\/code><br \/>\n<code>&gt;&gt;&gt; print(\"hello there!\")<\/code><br \/>\n<code>hello there!<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/p>\n<\/div>\n<h2><a id=\"_Toc519230981\"><\/a>Exceptions<\/h2>\n<p class=\"import-Normal\">Let us try to read input from the user. In the Python shell we enter the first line below and hit the Enter key. When the computer prompts for input, instead press [ctrl-c] (this example is with Windows) and see what happens.<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>&gt;&gt;&gt; text = input(\"Enter something: \")<\/code><br \/>\n<code>Enter something:<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#5&gt;\", line 1, in &lt;module&gt;<\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 text = input(\"Enter something: \")<\/code><br \/>\n<code style=\"color: #ff0000\">KeyboardInterrupt<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">Python raises an error called <code>KeyboardInterrupt<\/code> which basically means it was interrupted when it expected to get user input.<\/p>\n<p>Let us look at another example. Here we will read input from the user and then attempt to convert the string input into an integer.<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; num = input(\"Enter a number between 1 and 10: \")<\/code><br \/>\n<code>Enter a number between 1 and 10: no<\/code><br \/>\n<code>&gt;&gt;&gt; int(num)<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last):<\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#13&gt;\", line 1, in &lt;module&gt;<\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 int(num)<\/code><br \/>\n<code style=\"color: #ff0000\">ValueError: invalid literal for int() with base 10: 'no'<br \/>\n&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">Python raises an error called <code>ValueError<\/code> which is letting us know that the string <code>\u2019no\u2019<\/code> cannot be converted to an integer value. Programmers can avoid this scenario by checking that a string\u2019s value can be converted to a number value.<\/p>\n<p class=\"import-Normal\">Another common exception occurs when we try to evaluate a comparison which does not make sense. Consider the following Python conditional statements executed in the Shell window:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; 12 &gt; 5<\/code><br \/>\n<code>True<\/code><br \/>\n<code>&gt;&gt;&gt; 12 == 5<\/code><br \/>\n<code>False<\/code><br \/>\n<code>&gt;&gt;&gt; 12 &lt; 'a'<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"&lt;pyshell#2&gt;\", line 1, in &lt;module&gt; <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 \u00a012 &lt; 'a'<\/code><br \/>\n<code style=\"color: #ff0000\">TypeError: '&lt;' not supported between instances of 'int' and 'str'<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">Python raises an error called <code>TypeError<\/code> which is letting us know that the condition <code>12 &lt; 'a'<\/code> cannot be performed.<\/p>\n<h2><a id=\"_Toc519230982\"><\/a>Handling Exceptions<\/h2>\n<p class=\"import-Normal\">Essentially, exceptions are events that modify program\u2019s flow, either intentionally or due to errors. They are special events that can occur due to an error, e.g. trying to divide a number by zero. Exceptions, by definition, don\u2019t occur very often; hence, they are the \u201cexception to the rule\u201d.<\/p>\n<p class=\"import-Normal\">Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. One use of exceptions is to catch an error and allow the program to continue working instead of crashing ungracefully.<\/p>\n<p class=\"import-Normal\">This is the most common way to use exceptions. When programming with the Python command line interpreter (in the Shell window), you don\u2019t need to worry about catching exceptions. Your program is usually short enough to not be hurt too much if an exception occurs. Plus, having the exception occur at the command line is a quick and easy way to tell if your code logic has a problem. However, if the same error occurred in your saved .py file program, it will crash (fail) and stop working.<\/p>\n<p class=\"import-Normal\">Exceptions can be thought of as a special form of the <code>if-else<\/code> statements. You can realistically do the same thing with <code>if<\/code> blocks as you can with exceptions. However, as already mentioned, exceptions aren\u2019t processed until they occur; <code>if<\/code> blocks are processed all the time. Proper use of exceptions can help the performance of your program. The more infrequent the error might occur, the better off you are to use exceptions; using <code>if<\/code> blocks requires Python to always test extra conditions before continuing. Exceptions also make code management easier: if your programming logic is mixed in with error-handling <code>if<\/code> statements, it can be difficult to read, modify, and debug your program.<\/p>\n<p class=\"import-Normal\">We can handle exceptions using the <code>try-except-else<\/code> statement. Briefly, <code>try<\/code> creates a block that attempts to perform an action. If that action fails, the <code>except<\/code> block catches any exception that is raised and notifies the user that an error occurred, then stops executing the program. If the code within the try block does not produce an exception, the program\u2019s execution continues with code in the <code>else<\/code> block.<\/p>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230983\"><\/a><span class=\"import-Heading3Char\">Practice<\/span> &#8211; Here is a simple program that uses exception processing. It simply produces the quotient of 2 numbers. Try entering, saving and running the following program (<code>exceptionHandling.py<\/code>).<\/h2>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code># exception handling<\/code><br \/>\n<code>first_number = input ( \"Enter the first number: \") #gets input from keyboard<\/code><br \/>\n<code>sec_number = input ( \"Enter the second number: \" )<\/code><br \/>\n<code>try :<\/code><br \/>\n<code style=\"padding-left: 30px\">num1 = float( first_number ) #try turning keyboard input into floats<\/code><br \/>\n<code style=\"padding-left: 30px\">num2 = float( sec_number )<\/code><br \/>\n<code style=\"padding-left: 30px\">result = num1\/num2 #try dividing num1 by num2<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"Error: enter numbers only; num2 cannot equal zero\")<\/code><br \/>\n<code>else :<\/code><br \/>\n<code style=\"padding-left: 30px\">print(str(num1) + \"\/\" + str(num2) + \"=\" + str(result))<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">The output from executing this program, three separate times, is shown below.<\/p>\n<div class=\"textbox\"><code>\u00a0RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code><br \/>\n<code style=\"color: #333399\">Enter the first number: 33<\/code><br \/>\n<code style=\"color: #333399\">Enter the second number: 22<\/code><br \/>\n<code style=\"color: #333399\">33.0\/22.0=1.5<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code><br \/>\n<code style=\"color: #000080\">Enter the first number: 33<\/code><br \/>\n<code style=\"color: #000080\">Enter the second number: twenty<\/code><br \/>\n<code style=\"color: #000080\">Error: enter numbers only; num2 cannot equal zero<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/Dropbox\/OER Textbook\/TEXTBOOK OER\/Code\/exceptionHandling.py<\/code><br \/>\n<code style=\"color: #ff9900\">Enter the first number: 33<\/code><br \/>\n<code style=\"color: #ff9900\">Enter the second number: 0<\/code><br \/>\n<code style=\"color: #ff9900\">Error: enter numbers only; num2 cannot equal zero<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">In this example we simply print out a message to the user in the except block and then gracefully terminate our program. We use the <code>else<\/code> statement at the end to perform the rest of the program logic if all goes well. As stated before, the whole try block could also have been written as <code>if\/else<\/code> statements but that would have required Python to process each statement to see if they matched. By using exceptions, the \u201cdefault\u201d case is assumed to be true until an exception actually occurs. This speeds up processing.<\/p>\n<p class=\"import-Normal\">It\u2019s better to include error-checking, such as exceptions, in your code as you program rather than as an afterthought. A special \u201ccategory\u201d of programming involves writing test cases (we wrote test cases for our algorithms in Unit 1!) to ensure that most possible errors are accounted for in the code, especially as the code changes or new versions are created. Recall the test cases we were introduced to when writing our algorithms in Unit 1. By planning ahead and putting exception handling into your program at the outset, you ensure that problems are caught before they can cause problems.<\/p>\n<p class=\"import-Normal\">Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error (such as division by zero).<\/p>\n<h1><a id=\"_Toc519230984\"><\/a>Practice with Handling Exceptions in our Programs<\/h1>\n<p class=\"import-Normal\">Let us review some examples of handling exceptions in some of our programs we have written.<\/p>\n<h2><span class=\"import-Heading3Char\">Practice #1<\/span> &#8211; Calculating the distance between two points:<\/h2>\n<div class=\"textbox\">\n<p><code># calculates the distance between two points<\/code><\/p>\n<p><code>import math<\/code><\/p>\n<p><code>print(\"This program calculates the distance between two points.\")<\/code><br \/>\n<code>print() #print a blank line<\/code><\/p>\n<p><code>x1 = float(input(\"Enter the x for the first point: \"))<\/code><br \/>\n<code>y1 = float(input(\"Enter the y for the first point: \"))<\/code><br \/>\n<code>print()<\/code><br \/>\n<code>x2 = float(input(\"Enter the x for the second point: \"))<\/code><br \/>\n<code>y2 = float(input(\"Enter the y for the second point: \"))<\/code><\/p>\n<p><code>distance = math.sqrt((x2-x1)**2\u00a0 + (y2-y1)**2)<\/code><\/p>\n<p><code>print()<\/code><br \/>\n<code>print(\"The distance between the points is\", distance)<\/code><\/p>\n<\/div>\n<p>The output when executing this program with non-numeric input is seen below:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART:<\/code><br \/>\n<code>C:\/Users\/lh166266.UALBANY\/distanceBetweenPointsExceptionHandling.py<\/code><br \/>\n<code style=\"color: #333399\">This program calculates the distance between two points.<\/code><br \/>\n<code style=\"color: #333399\">Enter the x for the first point: 17<\/code><br \/>\n<code style=\"color: #333399\">Enter the y for the first point: 23<\/code><br \/>\n<code style=\"color: #333399\">Enter the x for the second point: 88<\/code><br \/>\n<code style=\"color: #333399\">Enter the y for the second point: 9p<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"C:\\Users\\lh166266.UALBANY\\distanceBetweenPoints.py\", line 12, in &lt;module&gt; <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 y2 = float(input(\"Enter the y for the second point: \"))<\/code><br \/>\n<code style=\"color: #ff0000\">ValueError: could not convert string to float: '9p'<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">Rewrite this program to include exception handling to catch the <code>ValueError<\/code> when we try and convert our user input into floating point numbers.<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code># Calculates the distance between two points<\/code><\/p>\n<p><code>import math<\/code><\/p>\n<p><code>print(\"This program calculates the distance between two points.\")<\/code><br \/>\n<code>print()<\/code><br \/>\n<code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">x1 = float(input(\"Enter the x for the first point: \"))<\/code><br \/>\n<code style=\"padding-left: 30px\">y1 = float(input(\"Enter the y for the first point: \"))<\/code><br \/>\n<code style=\"padding-left: 30px\">print()<\/code><br \/>\n<code style=\"padding-left: 30px\">x2 = float(input(\"Enter the x for the second point: \"))<\/code><br \/>\n<code style=\"padding-left: 30px\">y2 = float(input(\"Enter the y for the second point: \"))<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"Error: enter numeric values only\")<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)<\/code><br \/>\n<code style=\"padding-left: 30px\">print()<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"The distance between the points is\", distance)<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">The output when executing the revised program with non-numeric input is far more user friendly!<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART:<\/code><br \/>\n<code>C:\/Users\/lh166266.UALBANY\/distanceBetweenPointsExceptionHandling.py<\/code><br \/>\n<code style=\"color: #000080\">This program calculates the distance between two points.<\/code><br \/>\n<code style=\"color: #000080\">Enter the x for the first point: 17<\/code><br \/>\n<code style=\"color: #000080\">Enter the y for the first point: 23<\/code><br \/>\n<code style=\"color: #000080\">Enter the x for the second point: 88<\/code><br \/>\n<code style=\"color: #000080\">Enter the y for the second point:9p<\/code><br \/>\n<code style=\"color: #000080\">Error: enter numeric values only<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/p>\n<\/div>\n<h2><span class=\"import-Heading3Char\">Practice #<\/span><span class=\"import-Heading3Char\">2<\/span> \u2013 Guess the Number:<\/h2>\n<div class=\"textbox\">\n<p><code>number = 23<\/code><br \/>\n<code>guess = int(input('Enter an integer : '))<\/code><br \/>\n<code>if guess == number:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('Congratulations, you guessed it.')<\/code><br \/>\n<code style=\"padding-left: 30px\">print('(but you do not win any prizes!)')<\/code><br \/>\n<code>elif guess &lt; number:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('No, it is a little higher than that')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('No, it is a little lower than that')<\/code><\/p>\n<p><code>print('Done')<\/code><\/p>\n<\/div>\n<p>The output when executing this program with non-numeric input is seen below:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/ifElse.py<\/code><br \/>\n<code style=\"color: #000080\">Enter an integer : 8g6<\/code><br \/>\n<code style=\"color: #ff0000\">Traceback (most recent call last): <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 File \"C:\\Users\\lh166266.UALBANY\\Dropbox\\OER Textbook\\TEXTBOOK OER\\Code\\ifElse.py\", line 2, in &lt;module&gt; <\/code><br \/>\n<code style=\"color: #ff0000\">\u00a0 \u00a0 \u00a0 \u00a0 guess = int(input('Enter an integer : '))<\/code><br \/>\n<code style=\"color: #ff0000\">ValueError: invalid literal for int() with base 10: '8g6'<br \/>\n&lt;\/span style=\"color: #ff0000;\"&gt;&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\">Rewrite this program to include exception handling to catch the <code>ValueError<\/code> when we try and convert the user input into an integer.<\/p>\n<div class=\"textbox\">\n<p><code># Guess my number<\/code><\/p>\n<p><code>number = 23 .\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0#this is \u2018my number\u2019<\/code><br \/>\n<code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">guess = int(input('Enter an integer : '))<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"ERROR: enter whole numbers only\")<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">if guess == number:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('Congratulations, you guessed it.')<\/code><br \/>\n<code style=\"padding-left: 60px\">print('(but you do not win any prizes!)')<\/code><br \/>\n<code style=\"padding-left: 30px\">elif guess &lt; number:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('No, it is a little higher than that')<\/code><br \/>\n<code style=\"padding-left: 30px\">else:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('No, it is a little lower than that')<\/code><\/p>\n<p><code>print('Done')<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">The output when executing the revised program with non-numeric input gracefully ends rather than crashing!<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART: C:\/Users\/lh166266.UALBANY\/ifElseExceptionHandling.py<\/code><br \/>\n<code style=\"color: #003366\">Enter an integer : 88m<\/code><br \/>\n<code style=\"color: #003366\">ERROR: enter whole numbers only<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<h1><a id=\"_Toc519230987\"><\/a>Iteration<\/h1>\n<p class=\"import-Normal\">This section is about iteration, which is the ability to run a block of statements repeatedly. Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration.<\/p>\n<h2><a id=\"_Toc519230988\"><\/a>The while Statement<\/h2>\n<p class=\"import-Normal\">A <code>while<\/code> statement is an iterative control statement that repeatedly executes a set of statements based on a provided Boolean expression (condition). All iterative control needed in a program can be achieved by use of the <code>while<\/code> statement, though, as we will see later, other iterative control statements can be more useful for solving some computational problems.<\/p>\n<p>Here is a version of a countdown function that uses a while statement:<\/p>\n<div class=\"textbox\">\n<p><code>def countdown(n):<\/code><br \/>\n<code style=\"padding-left: 30px\">while n &gt; 0:<\/code><br \/>\n<code style=\"padding-left: 60px\">print(n)<\/code><br \/>\n<code style=\"padding-left: 60px\">n = n - 1<\/code><br \/>\n<code style=\"padding-left: 30px\">print('Blastoff!')<\/code><\/p>\n<\/div>\n<div style=\"width: 381px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161439\/image47.png\" alt=\"image\" width=\"371\" height=\"376\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 45: While Loop Flowchart<\/p>\n<\/div>\n<p><small>\u00a0<\/small>You can almost read the <code>while<\/code> statement as if it were English. It means, \u201cWhile n is greater than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!\u201d<\/p>\n<p class=\"import-Normal\">Here is the flow of execution for a while statement:<\/p>\n<ol>\n<li>Determine whether the condition is true or false.<\/li>\n<li>If false, exit the while statement and continue execution at the next statement.<\/li>\n<li>If the condition is true, run the body and then go back to step 1.<\/li>\n<\/ol>\n<p class=\"import-Normal\">This type of flow is called a loop because the third step loops back around to the top.<\/p>\n<p class=\"import-Normal\">The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an <strong>infinite<\/strong> loop.<\/p>\n<p class=\"import-Normal\">In the case of the countdown function, we can prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.<\/p>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230989\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 1<\/span>: Try executing the following program which uses the countdown function (<code>countdown.py<\/code>).<\/h2>\n<div class=\"textbox\">\n<p><code>def countdown(n):<\/code><br \/>\n<code style=\"padding-left: 30px\">while n &gt; 0:<\/code><br \/>\n<code style=\"padding-left: 60px\">print(n)<\/code><br \/>\n<code style=\"padding-left: 60px\">n = n - 1<\/code><br \/>\n<code style=\"padding-left: 30px\">print('Blastoff!')<\/code><br \/>\n<code>num = input(\"enter a positive number to countdown from: \")<\/code><\/p>\n<p><code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">num=int(num)<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"ERROR: enter a whole number\")<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">countdown(num)<\/code><\/p>\n<\/div>\n<p>An example of the output after execution:<\/p>\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/countdown.py<\/code><br \/>\n<code style=\"color: #003366\">enter a number to countdown from: 9<\/code><br \/>\n<code style=\"color: #003366\">9<\/code><br \/>\n<code style=\"color: #003366\">8<\/code><br \/>\n<code style=\"color: #003366\">7<\/code><br \/>\n<code style=\"color: #003366\">6<\/code><br \/>\n<code style=\"color: #003366\">5<\/code><br \/>\n<code style=\"color: #003366\">4<\/code><br \/>\n<code style=\"color: #003366\">3<\/code><br \/>\n<code style=\"color: #003366\">2<\/code><br \/>\n<code style=\"color: #003366\">1<\/code><br \/>\n<code> style=\"color: #003366;\"&gt;Blastoff!<\/code><br \/>\n<code>&gt;&gt;<\/code>&gt;<\/div>\n<p class=\"import-Normal\">The variable <code style=\"font-weight: bold\">n<\/code> in the <code>countdown.py<\/code> program is referred to as a <em>counter<\/em>. A <em>counter<\/em> variable is used to count something, usually initialized to zero and then incremented (or decremented) and is commonly used in programs.<\/p>\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>while<\/code> statement allows you to repeatedly execute a block of statements as long as a condition is true. A <code>while<\/code> statement is an example of what is called a <em lang=\"en\" xml:lang=\"en\">looping<\/em><span lang=\"en\" xml:lang=\"en\"> statement. A <\/span><code>while<\/code><span lang=\"en\" xml:lang=\"en\"> statement can have an optional else clause.<\/span><span lang=\"en\" xml:lang=\"en\"> Let us look at the following program (<\/span><code>while.py<\/code>)<\/p>\n<div class=\"textbox\">\n<p><code>number = 23<\/code><br \/>\n<code>running = True<\/code><\/p>\n<p><code>while running:<\/code><br \/>\n<code style=\"padding-left: 30px\">guess = int(input('Enter an integer : '))<\/code><br \/>\n<code style=\"padding-left: 30px\">if guess == number:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('Congratulations, you guessed it.')<\/code><br \/>\n<code style=\"padding-left: 60px\"># this causes the while loop to stop<\/code><br \/>\n<code style=\"padding-left: 60px\">running = False<\/code><br \/>\n<code style=\"padding-left: 30px\">elif guess &lt; number:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('No, it is a little higher than that.')<\/code><br \/>\n<code style=\"padding-left: 30px\">else:<\/code><br \/>\n<code style=\"padding-left: 60px\">print('No, it is a little lower than that.')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('The while loop is over.')<\/code><br \/>\n<code style=\"padding-left: 30px\"># Do anything else you want to do here<\/code><\/p>\n<p><code>print('Done')<\/code><\/p>\n<\/div>\n<\/div>\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly &#8211; there is no need to repeatedly run the program for each guess, as we have done in the previous section. This aptly demonstrates the use of the <\/span><code>while<\/code><span lang=\"en\" xml:lang=\"en\"> statement.<\/span>Let us examine more closely the code in this program <span lang=\"en\" xml:lang=\"en\">(<\/span><code>while.py<\/code><span lang=\"en\" xml:lang=\"en\">)<\/span>.<\/p>\n<table style=\"height: 1172px\">\n<tbody>\n<tr class=\"TableGrid-R\" style=\"height: 73px\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px\">\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px\">\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 188px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 188px\">\n<p class=\"import-Normal\"><code>number = 23<\/code><\/p>\n<p class=\"import-Normal\"><code>running = True<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 188px\">\n<p class=\"import-Normal\">We set the variable number to a number we want; here we choose the number \u201823\u2019.The variable running is referred to as a \u2018flag\u2019 variable. Flag variables go by many different names, but they all represent a variable (usually of <code>Boolean<\/code> type) that can only be one of two states, <code>True<\/code> or <code>False<\/code>.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 208px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 208px\">\n<p class=\"import-Normal\"><code>while running<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 208px\">\n<p class=\"import-Normal\">This where the loop starts.<\/p>\n<p class=\"import-Normal\">First, we check if the variable <code>running<\/code> is <code>True<\/code> and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the <code>running<\/code> variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 604px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 604px\">\n<p class=\"import-Normal\"><code>guess =<\/code> <code>int(input('Enter an integer : '))<\/code><\/p>\n<p class=\"import-Normal\"><code>if guess == number:<\/code><\/p>\n<p class=\"import-Normal\"><code>print('Congratulations, you guessed it.')<\/code><\/p>\n<p class=\"import-Normal\"><code>running = False<\/code><\/p>\n<p class=\"import-Normal\"><code>elif guess &lt; number:<\/code><\/p>\n<p class=\"import-Normal\"><code>print('No, it is a little higher than that.')<\/code><\/p>\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\n<p class=\"import-Normal\"><code>print('No, it is a little lower than that.')<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 604px\">\n<p class=\"import-Normal\">This is the \u2018body\u2019 of the entire loop.<\/p>\n<p class=\"import-Normal\">The user is asked to enter an integer number which is converted into an integer and saved in the variable <code>guess<\/code>.<\/p>\n<p class=\"import-Normal\">Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message and set our flag variable, <code>running<\/code>, to <code>False<\/code>. This will soon cause the while loop to stop.<\/p>\n<p class=\"import-Normal\">Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that.<\/p>\n<p class=\"import-Normal\">Finally we check if the guess is greater than the number, and if so, we inform the user that they must guess a little lower than that.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 99px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 99px\">\n<p class=\"import-Normal\"><code>print('Done')<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 99px\">\n<p class=\"import-Normal\">Once we have exited the while loop we print this single statement to indicate to the user that the guessing game is over.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"import-Normal\">The following is a sample of output after running this program:<\/p>\n<div class=\"textbox\"><code style=\"color: #003366\">Enter an integer : 5<\/code><br \/>\n<code style=\"color: #003366\">No, it is a little higher than that.<\/code><br \/>\n<code style=\"color: #003366\">Enter an integer : 19<\/code><br \/>\n<code style=\"color: #003366\">No, it is a little higher than that.<\/code><br \/>\n<code style=\"color: #003366\">Enter an integer:25 <\/code><br \/>\n<code style=\"color: #003366\">No, it is a little lower than that.<\/code><br \/>\n<code style=\"color: #003366\">Enter an integer:24<\/code><br \/>\n<code style=\"color: #003366\">No, it is a little lower than that.<\/code><br \/>\n<code style=\"color: #003366\">Enter an integer: 23<\/code><br \/>\n<code style=\"color: #003366\">Congratulations, you guessed it.<\/code><br \/>\n<code style=\"color: #003366\">The while loop is over. Done<\/code><br \/>\n&gt;&gt;&gt;<\/div>\n<p class=\"import-Normal\">This is an example of an <em>interactive loop<\/em> because it allows the user to repeat something (in this example the user is guessing a number) on demand.<\/p>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230990\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 2<\/span>: The following program allows a user to enter any number of nonnegative integers. When the user enters a negative value, the program no longer accepts input, and it displays the sum of all the nonnegative values. If a negative number is the first entry, the sum is zero. This is also an example of <em>interactive loop<\/em>. [<code>addNonNegatives.py<\/code>]<\/h2>\n<div class=\"textbox\"><code># Allow the user to enter a sequence of nonnegative integers to sum.<\/code><br \/>\n<code>entry = 0\u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code> # Ensure the loop is entered<\/code><br \/>\n<code>sum = 0<\/code>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># Initialize sum<\/code><br \/>\n<code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><br \/>\n<code>while entry &gt;= 0:\u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># A negative number exits the loop<\/code><br \/>\n<code>entry = int(input(\"number: \")) # Get the value<\/code><br \/>\n<code>if entry &gt;= 0:\u00a0 \u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code># Is number nonnegative?<\/code><br \/>\n<code>sum = sum entry<\/code><br \/>\n<code>print(\"Sum =\", sum)<\/code>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code># Display the sum<\/code><\/div>\n<div class=\"textbox\"><code>RESTART:C:\/Users\/lh166266.UALBANY\/Code\/addNonNegatives.py<\/code><br \/>\n<code style=\"color: #000080\">Enter positive numbers to sum (entering a negative number ends the program).<\/code><br \/>\n<code style=\"color: #000080\">number: 8 <\/code><br \/>\n<code style=\"color: #000080\">number: 9<\/code><br \/>\n<code style=\"color: #000080\">number: 1<\/code><br \/>\n<code style=\"color: #000080\">number: 2<\/code><br \/>\n<code style=\"color: #000080\">number: -9<\/code><br \/>\n<code style=\"color: #000080\">Sum = 20<\/code><\/div>\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 46: Sample Output from addNonNegatives.py<\/em><\/p>\n<div style=\"width: 530px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161441\/image48.png\" alt=\"image\" width=\"520\" height=\"595\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 47: While Loop Flowchart<\/p>\n<\/div>\n<p><small>\u00a0<\/small>Let us examine more closely the code in this program.<\/p>\n<table style=\"height: 485px\">\n<tbody>\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 154.625px\">\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 729.625px\">\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 73px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px;width: 154.625px\">\n<p class=\"import-Normal\"><code>entry = 0<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 73px;width: 729.625px\">\n<p class=\"import-Normal\">In the beginning we initialize <code>entry<\/code> to zero for the sole reason that we want the condition <code>entry &gt;= 0<\/code> of the while statement to be <code>true<\/code> initially. If we fail to initialize <code>entry<\/code>, the program will produce a run-time error when it attempts to compare <code>entry<\/code> to zero in the while condition. The <code>entry<\/code> variable holds the number entered by the user. Its value can change each time through the loop.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 75px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 75px;width: 154.625px\">\n<p class=\"import-Normal\"><code>sum = 0<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 75px;width: 729.625px\">\n<p class=\"import-Normal\">The variable <code>sum<\/code> is known as an <em>accumulator<\/em> because it accumulates each value the user enters. We initialize <code>sum<\/code> to zero in the beginning because a value of zero indicates that it has not accumulated anything. If we fail to initialize <code>sum<\/code>, the program will generate a run-time error when it attempts to use the + operator to modify the (non-existent) variable.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 89px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 89px;width: 154.625px\">\n<p class=\"import-Normal\"><code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 89px;width: 729.625px\">\n<p class=\"import-Normal\">This statement provides instructions for this app.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 161px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 161px;width: 154.625px\">\n<p class=\"import-Normal\"><code>while entry &gt;= 0:<\/code><\/p>\n<p class=\"import-Normal\"><code>entry = int(input(\"number: \"))<\/code><\/p>\n<p class=\"import-Normal\"><code>if entry &gt;= 0:<\/code><\/p>\n<p class=\"import-Normal\"><code>sum = sum + entry<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 161px;width: 729.625px\">\n<p class=\"import-Normal\">Within the loop we repeatedly add the user\u2019s input values to <code>sum<\/code>. When the loop finishes (because the user entered a negative number), <code>sum<\/code> holds the <code>sum<\/code> of all the nonnegative values entered by the user.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 44px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 44px;width: 154.625px\">\n<p class=\"import-Normal\"><code>print(\"Sum =\", sum)<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 44px;width: 729.625px\">\n<p class=\"import-Normal\">Once we have exited the <code>while<\/code> loop we print this single statement to indicate to the user what the sum of all the numbers entered is.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230991\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 3<\/span>: Now let us rewrite this program to add additional functionality. In addition to finding the sum of nonnegative values we will calculate the average. [<code>avgNonNegatives.py<\/code>]<\/h2>\n<div class=\"textbox\"><code># Allow the user to enter a sequence of nonnegative integers to sum and find the average.<\/code><br \/>\n<code>entry = 0\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Ensure the loop is entered<\/code><br \/>\n<code>sum = 0\u00a0\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 <code># Initialize sum<\/code><br \/>\n<code>count = 0\u00a0<\/code>\u00a0\u00a0\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\u00a0 <code># Initialize count<\/code><br \/>\n<code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><br \/>\n<code>while entry &gt;= 0:\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 <code># A negative number exits the loop<\/code><br \/>\n<code>entry = int(input(\"number: \"))\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Get the value<\/code><br \/>\n<code>if entry &gt;= 0: \u00a0<\/code> \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0<code>\u00a0 # Is number nonnegative?<\/code><br \/>\n<code>sum = sum + entry\u00a0<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> # Only add it if it is nonnegative<\/code><br \/>\n<code>count = count + 1<\/code>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<code> #increment the count of numbers entered<\/code><br \/>\n<code>print(\"Sum =\", sum) # Display the sum<\/code><br \/>\n<code>average = sum \/ count<\/code><br \/>\n<code>print(\"Average =\", average)<\/code><\/div>\n<p class=\"import-Normal\">The program needs not only an accumulator variable (i.e. <code>sum<\/code>) but a counter variable also (named <code>count<\/code>) to keep track of how many numbers have been entered. We can then calculate the average by dividing the sum by the count.<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/avgNonNegatives.py<\/code><br \/>\n<code>Enter positive numbers to sum (entering a negative number ends the program).<\/code><br \/>\n<code style=\"color: #000080\">number:<\/code><code>12<\/code><br \/>\n<code style=\"color: #000080\">number:<\/code><code>55<\/code><br \/>\n<code style=\"color: #000080\">number:<\/code><code>31<\/code><br \/>\n<code style=\"color: #000080\">number:<\/code><code>-11<\/code><br \/>\n<code style=\"color: #000080\"><\/code><code>Sum = 98<\/code><br \/>\n<code style=\"color: #000080\">Average = 32.666666666666664<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 48: Sample Output from avgNonNegatives.py<\/em><\/p>\n<h2><a id=\"_Toc519230992\"><\/a>The break Statement<\/h2>\n<p class=\"import-Normal\">Sometimes you don\u2019t know it\u2019s time to end a loop until you get half way through the body. In that case you can use the <code>break<\/code> statement to jump out of the loop.<\/p>\n<p>For example, suppose you want to take input from the user until they type <code>done<\/code>. You could write:<\/p>\n<div class=\"textbox\"><code>while True:<\/code><br \/>\n<code>line = input('&gt; ')<\/code><br \/>\n<code>if line == 'done':<\/code><br \/>\n<code>break<\/code><br \/>\n<code>print(line)print('Done!')<\/code><\/div>\n<p class=\"import-Normal\">The loop condition is <code>True<\/code>, which is always true, so the loop runs until it hits the <code>break<\/code> statement.<\/p>\n<p>Each time through, it prompts the user with an angle bracket. If the user types done, the <code>break<\/code> statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here\u2019s a sample run:<\/p>\n<div class=\"textbox\"><code>&gt; hello<\/code><br \/>\n<code>hello<\/code><br \/>\n<code>&gt; done<\/code><br \/>\n<code>Done!<\/code><\/div>\n<p class=\"import-Normal\">This way of writing <code>while<\/code> loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (\u201cstop when this happens\u201d) rather than negatively (\u201ckeep going until that happens\u201d).<\/p>\n<p class=\"import-Normal\">Note that the <code>break<\/code> statement works with the for loop as well.<\/p>\n<h2><a id=\"_Toc519230993\"><\/a>The continue Statement<\/h2>\n<p class=\"import-Normal\">The <code>continue<\/code> statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.<\/p>\n<p>Let us examine the following example (save as <code>continue.py<\/code>):<\/p>\n<div class=\"textbox\">\n<p><code># user is to enter a string of at minimum 3 words<\/code><br \/>\n<code># to end the user is to enter the word 'quit'<\/code><br \/>\n<code>while True:<\/code><br \/>\n<code><code style=\"padding-left: 30px\">data = input('Enter at least 3 words: ')<\/code><\/code><br \/>\n<code><code style=\"padding-left: 30px\">if data == 'quit':<\/code><\/code><br \/>\n<code><code style=\"padding-left: 60px\">break<\/code><\/code><br \/>\n<code><code style=\"padding-left: 30px\">if len(data) &lt; 3:<\/code><\/code><br \/>\n<code><code style=\"padding-left: 60px\">print('Too small')<\/code><\/code><br \/>\n<code><code style=\"padding-left: 60px\">continue<\/code><\/code><br \/>\n<code>print('Input (data) is of sufficient length')<\/code><br \/>\n<code># Do other kinds of processing here...<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">Sample Output:<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt;<\/code><br \/>\n<code>RESTART:C:\/Users\/lh166266.UALBANY\/Code\/continue.py<\/code><br \/>\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> hi<\/code><br \/>\n<code><code style=\"color: #000080\">Too small<\/code><\/code><br \/>\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> how are you<\/code><br \/>\n<code><code style=\"color: #000080\">Input (data) is of sufficient length<\/code><\/code><br \/>\n<code><code style=\"color: #000080\">Enter at least 3 words:<\/code> quit<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p>In this program, we accept input from the user, but we process the input string only if it is at least 3 words long or the user enters the word \u2018quit\u2019. So, we use the built-in <code>len<\/code> function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the <code>continue<\/code> statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing we want to do here. When the user enters the word \u2018<code>quit\u2019<\/code> we exit the loop using the <code>break<\/code> statement, then end the program. This is an example of an <em>input validation loop<\/em>. In an <em>input validation loop<\/em> (commonly designed using the <code>while<\/code> loop) the program inspects user input before it is processed by the program and if input is invalid it prompts user to enter correct data.<\/p>\n<p class=\"import-Normal\">Note that the <code>continue<\/code> statement works with the <code>for<\/code> loop as well.<\/p>\n<h1><a id=\"_Toc519230994\"><\/a>The for&#8230;in Statement<\/h1>\n<p class=\"import-Normal\">The <code>for..in<\/code> statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. Recall that a sequence is just an ordered collection of items. Let us look at the following program, <code>for.py<\/code>.<\/p>\n<div class=\"textbox\">\n<p><code>for i in range(1, 5):<\/code><br \/>\n<code><code style=\"padding-left: 30px\">print(i)<\/code><\/code><br \/>\n<code>else:<\/code><br \/>\n<code><code style=\"padding-left: 30px\">print('The for loop is over')<\/code><\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">This is what the output of the program looks like in the Python shell after it runs:<\/p>\n<div class=\"textbox\"><code>1<\/code><br \/>\n<code>2<\/code><br \/>\n<code>3<\/code><br \/>\n<code>4<\/code><br \/>\n<code>The for loop is over<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> function.<\/span><\/p>\n<p class=\"import-Normal\"><span lang=\"en\" xml:lang=\"en\">What we do here is supply it two numbers and <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> returns a sequence of numbers starting from the first number and up to the second number. For example, <\/span><span lang=\"en\" xml:lang=\"en\"><code>range<\/code>(<code>1,5<\/code>)<\/span><span lang=\"en\" xml:lang=\"en\"> gives the sequence <\/span><span lang=\"en\" xml:lang=\"en\"><code>[1, 2, 3, 4]<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> By default, <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\"> takes a step count of <code>1<\/code>. If we supply a third number to <\/span><code><span lang=\"en\" xml:lang=\"en\">range<\/span><\/code><span lang=\"en\" xml:lang=\"en\">, then that becomes the step count. For example<\/span><span lang=\"en\" xml:lang=\"en\">, <code>range(1,5,2)<\/code><\/span><span lang=\"en\" xml:lang=\"en\"> gives <\/span><span lang=\"en\" xml:lang=\"en\"><code>[1,3]<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> Remember that the <\/span><code>range<\/code><span lang=\"en\" xml:lang=\"en\"> extends up to the second number i.e. it does not include the second number.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop then iterates over this range &#8211; <\/span><code>for i in range(1,5)<\/code><span lang=\"en\" xml:lang=\"en\"> is equivalent to <\/span><code>for i in [1, 2, 3, 4]<\/code><span lang=\"en\" xml:lang=\"en\">which is like assigning each number (or object) in the sequence to <\/span><span lang=\"en\" xml:lang=\"en\"><code>i<\/code>,<\/span><span lang=\"en\" xml:lang=\"en\"> one at a time, and then executing the block of statements for each value of <\/span><span lang=\"en\" xml:lang=\"en\"><code>i<\/code>.<\/span><span lang=\"en\" xml:lang=\"en\"> In this case, we just print the value in the block of statements.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The general form of the <code>range<\/code> expression is <\/span><code>range( begin,end,step )<\/code><span lang=\"en\" xml:lang=\"en\"> where<\/span><\/p>\n<ul>\n<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>begin<\/code><span lang=\"en\" xml:lang=\"en\"> is the first value in the range; if omitted, the default value is 0<\/span><\/li>\n<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>end<\/code><span lang=\"en\" style=\"text-align: initial;font-size: 1em\" xml:lang=\"en\"> is one past the last value in the range; the end value is always required and may not be omitted<\/span><\/li>\n<li class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>step<\/code><span lang=\"en\" style=\"text-align: initial;font-size: 1em\" xml:lang=\"en\"> is the amount to increment or decrement; if the step parameter is omitted, it defaults to 1 (counts up by ones)<\/span><\/li>\n<\/ul>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><code>begin<\/code><span lang=\"en\" xml:lang=\"en\">, <\/span><code>end<\/code><span lang=\"en\" xml:lang=\"en\">, and <code>step<\/code> must all be integer expressions; floating-point expressions and other types are not allowed. The arguments in the range expression may be literal numbers (like 10), variables (like<\/span><span lang=\"en\" xml:lang=\"en\"> x<\/span><span lang=\"en\" xml:lang=\"en\">, if <\/span><span lang=\"en\" xml:lang=\"en\">x<\/span><span lang=\"en\" xml:lang=\"en\"> is <\/span><span lang=\"en\" xml:lang=\"en\">equal<\/span><span lang=\"en\" xml:lang=\"en\"> to an integer), and arbitrarily complex integer expressions.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The <\/span><code>range<\/code><span lang=\"en\" xml:lang=\"en\"> expression is very flexible. Consider the following loop that counts down from 21 to 3 by threes:<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code>for n in range(21, 0, -3):<br \/>\nprint(n, end=' ')<\/code><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">It prints: <\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff;text-indent: 36pt\"><code>21 18 15 12 9 6 3<\/code><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">Thus <\/span><code>range(21, 0, -3)<\/code><span lang=\"en\" xml:lang=\"en\"> represents the sequence <\/span><span lang=\"en\" xml:lang=\"en\"><code>21;18;15;12;9; 3<\/code>.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The expression <\/span><code>range(1000)<\/code><span lang=\"en\" xml:lang=\"en\"> produces the sequence <\/span><code>0;1;2; : : : ; 999.<\/code><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">The following code computes and prints the sum of all the positive integers less than 100:<\/span><\/p>\n<p><code style=\"padding-left: 30px\">sum = 0 # Initialize sum<\/code><br \/>\n<code style=\"padding-left: 30px\">for i in range(1, 100):<\/code><br \/>\n<code style=\"padding-left: 60px\">sum += i<\/code><br \/>\n<code style=\"padding-left: 60px\">print(sum)<\/code><\/p>\n<p><span lang=\"en\" xml:lang=\"en\">Remember that the <\/span><code>else<\/code> <span lang=\"en\" xml:lang=\"en\">block<\/span><span lang=\"en\" xml:lang=\"en\"> is optional. When included, it is always executed once after the <\/span><span lang=\"en\" xml:lang=\"en\">for<\/span><span lang=\"en\" xml:lang=\"en\"> loop is over unless a <\/span><a class=\"rId98\" href=\"#break-statement\"><code>break<\/code><\/a><span lang=\"en\" xml:lang=\"en\"> statement is encountered.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\">So far we have used the <code>for<\/code> loop to iterate over integer sequences because this is a useful and common task in developing apps. The <code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop, however, can iterate over any iterable object<\/span><span lang=\"en\" xml:lang=\"en\">, such as a string<\/span><span lang=\"en\" xml:lang=\"en\">.<\/span><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">We can use a <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop to iterate over the characters that comprise a string. <\/span><span lang=\"en\" xml:lang=\"en\">The following program<\/span><span lang=\"en\" xml:lang=\"en\"> uses a <\/span><code>for<\/code><span lang=\"en\" xml:lang=\"en\"> loop to print the individual characters of a string<\/span><code> (printLetters.py<span lang=\"en\" xml:lang=\"en\">)<\/span><\/code><span lang=\"en\" xml:lang=\"en\">.<\/span><\/p>\n<p><code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code lang=\"en\" xml:lang=\"en\">word = input('Enter a word: ')<\/code><\/code><br \/>\n<code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt\"><code lang=\"en\" xml:lang=\"en\">for letter in word:<\/code><\/code><br \/>\n<code class=\"import-comments-section\" style=\"background-color: #ffffff;margin-left: 36pt;padding-left: 30px\"><code lang=\"en\" xml:lang=\"en\"> print(letter)<\/code><\/code><\/p>\n<p class=\"import-comments-section\" style=\"background-color: #ffffff\"><span lang=\"en\" xml:lang=\"en\">Sample output<\/span><span lang=\"en\" xml:lang=\"en\">: <\/span><\/p>\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/printLetters.py<\/code><br \/>\n<code style=\"color: #000080\">Enter a word: hello<\/code><br \/>\n<code style=\"color: #000080\">h<\/code><br \/>\n<code style=\"color: #000080\">e<\/code><br \/>\n<code style=\"color: #000080\">l<\/code><br \/>\n<code style=\"color: #000080\">l<\/code><br \/>\n<code style=\"color: #000080\">o<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p>&nbsp;<\/p>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230995\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 1<\/span>: Write a program to solve the following problem. <code>[printWords.py]<\/code><\/h2>\n<div class=\"textbox\">Problem: Ask the user how many words they want to enter then print the words entered by the user on one line separated by spaces.<br \/>\nInput: Number of words to be entered; this value must be a positive integer greater than zero.<\/div>\n<p>&nbsp;<\/p>\n<div class=\"textbox\">\n<p><code># Ask the user how many words they want to enter<\/code><br \/>\n<code># then print the words together on one line.<\/code><br \/>\n<code>sentence = \"\"<\/code><br \/>\n<code>num = input(\"How many words do you want to enter? \")<\/code><br \/>\n<code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">num=int(num)<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print (\"ERROR: enter a number\")<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">if num &gt; 0: #check for a positive number<\/code><br \/>\n<code style=\"padding-left: 60px\">for i in range(num):<\/code><br \/>\n<code style=\"padding-left: 90px\">word = input(\"enter a word: \")<\/code><br \/>\n<code style=\"padding-left: 90px\">sentence = sentence + \" \" + word<\/code><br \/>\n<code style=\"padding-left: 60px\">print(sentence)<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"Will only accept a positive integer number. Ending program\")<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Note the error checking performed in the program:<\/p>\n<ul>\n<li>Ensures the user only enters integer numbers as input<\/li>\n<li>Ensures the user enters a positive integer<\/li>\n<\/ul>\n<h2 class=\"import-Normal\"><a id=\"_Toc519230996\"><\/a><span class=\"import-Heading3Char\">Practice<\/span><span class=\"import-Heading3Char\"> 2<\/span>: Write a program to solve the following problem. <code>[numWords.py]<\/code><\/h2>\n<div class=\"textbox\">Problem: Ask the user to enter in a complete sentence and display the number of words in the sentence.<\/div>\n<p class=\"import-Normal\">Unlike <span lang=\"en\" xml:lang=\"en\">the example where we<\/span><span lang=\"en\" xml:lang=\"en\"> use<\/span><span lang=\"en\" xml:lang=\"en\">d<\/span><span lang=\"en\" xml:lang=\"en\"> a <\/span><span lang=\"en\" xml:lang=\"en\">for<\/span><span lang=\"en\" xml:lang=\"en\"> loop to iterate over the characters <\/span><span lang=\"en\" xml:lang=\"en\">of a word, we need to use a string object\u2019s method to break the string into words.<\/span> <span lang=\"en\" xml:lang=\"en\">When you need to break a large string down into smaller chunks, or strings<\/span><span lang=\"en\" xml:lang=\"en\">,<\/span><span lang=\"en\" xml:lang=\"en\"> you use the <\/span><code>split()<\/code><span lang=\"en\" xml:lang=\"en\"> string method. By default, <\/span><code>split()<\/code><span lang=\"en\" xml:lang=\"en\"> takes whitespace as the delimiter.<\/span><span lang=\"en\" xml:lang=\"en\"> Try executing this program<\/span><code><span lang=\"en\" xml:lang=\"en\"> <code>(numWords.py)<\/code><\/span><\/code><\/p>\n<div class=\"textbox\"><code># Ask the user to enter in a complete sentence and display the number of words in the sentence.<\/code><br \/>\n<code>sentence = input(\"please enter an awe inspiring sentence or two: \")<\/code><br \/>\n<code>words = sentence.split()<\/code><br \/>\n<code>print(\"you entered\", len(words), \"words\")<\/code><br \/>\n<code>print(\"here are the individual words you entered:\", words)<\/code><\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Example output:<\/p>\n<div class=\"textbox\"><code style=\"color: #0000ff\">please enter an awe inspiring<\/code><code style=\"color: #0000ff\">sentence or two:<\/code><code> When I need to build a web app, I reach for the Python programming language. When I need to automate some small task on my system, I reach for Python. Python rocks!<\/code><br \/>\n<code style=\"color: #0000ff\">you entered 32 words<\/code><br \/>\n<code style=\"color: #0000ff\">here are the individual words you entered: ['When', 'I', 'need', 'to', 'build', 'a', 'web', 'app,', 'I', 'reach', 'for', 'the', 'Python', 'programming', 'language.', 'When', 'I', 'need', 'to', 'automate', 'some', 'small', 'task', 'on', 'my', 'system,', 'I', 'reach', 'for', 'Python.', 'Python', 'rocks!']<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Once you have used <code>split<\/code> to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.<\/p>\n<div class=\"textbox\"><code>&gt;&gt;&gt; sentence = \"Python is a general purpose programming language named after Monty Python.\"<\/code><br \/>\n<code>&gt;&gt;&gt; words = sentence.split()<\/code><br \/>\n<code>&gt;&gt;&gt; print(words)<\/code><br \/>\n<code style=\"color: #0000ff\">['Python', 'is', 'a', 'general', 'purpose', 'programming', 'language', 'named', 'after', 'Monty', 'Python.']<\/code><br \/>\n<code>&gt;&gt;&gt; print(words[9], words[3], words[6])<\/code><br \/>\n<code style=\"color: #0000ff\">Monty general language<\/code><br \/>\n&gt;&gt;&gt;<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Enhance this program to loop through each word in the list named words and print each word in uppercase on its own line <span lang=\"en\" xml:lang=\"en\">(<\/span><code>uppercaseWords.py<\/code>.<\/p>\n<div class=\"textbox\"><code># Ask the user to enter in a complete sentence and display each work in uppercase.<\/code><br \/>\n<code>sentence = input(\"please enter an awe inspiring sentence or two: \")<\/code><br \/>\n<code>words = sentence.split()<\/code><br \/>\n<code>print(\"you entered\", len(words), \"words\")<\/code><br \/>\n<code>print(\"here are the individual words you entered:\")for word in words:<\/code><br \/>\n<code>print(word.upper())<\/code><\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Example output:<\/p>\n<div class=\"textbox\"><code style=\"color: #0000ff\">please enter an awe inspiring sentence or two:<\/code><code>Python is a general purpose programming language named after Monty Python.<\/code><br \/>\n<code style=\"color: #0000ff\">you entered 11 words<\/code><br \/>\n<code style=\"color: #0000ff\">here are the individual words you entered:<\/code><br \/>\n<code style=\"color: #0000ff\">PYTHON<\/code><br \/>\n<code style=\"color: #0000ff\">IS<\/code><br \/>\n<code style=\"color: #0000ff\">A<\/code><br \/>\n<code style=\"color: #0000ff\">GENERAL<\/code><br \/>\n<code style=\"color: #0000ff\">PURPOSE<\/code><br \/>\n<code style=\"color: #0000ff\">PROGRAMMING<\/code><br \/>\n<code style=\"color: #0000ff\">LANGUAGE<\/code><br \/>\n<code style=\"color: #0000ff\">NAMED<\/code><br \/>\n<code style=\"color: #0000ff\">AFTER<\/code><br \/>\n<code style=\"color: #0000ff\">MONTYPYTHON.<\/code><br \/>\n&gt;&gt;&gt;<\/div>\n<p>&nbsp;<\/p>\n<div class=\"textbox\">\n<p><strong>How to choose between the <code>for<\/code> and <code>while<\/code> loop?<\/strong><\/p>\n<p>Use a <code>for<\/code> loop if you know, before you start looping, the maximum number of times that you\u2019ll need to execute the body. For example, if you\u2019re traversing a list of elements, you know that the maximum number of loop iterations you can possibly need is \u201call the elements in the list\u201d. Or if you need to print the 12 times table, we know right away how many times the loop will need to run.<\/p>\n<p>So any problem like \u201citerate this weather model for 1000 cycles\u201d, or \u201csearch this list of words\u201d, \u201cfind all prime numbers up to 10000\u201d suggest that a <code>for<\/code> loop is best.<\/p>\n<p>By contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, as we did in this 3n + 1 problem, you\u2019ll need a <code>while<\/code> loop.<\/p>\n<p>We call the first case <strong>definite<\/strong> <strong>iteration<\/strong> \u2014 we know ahead of time some definite bounds for what is needed. The latter case is called <strong>indefinite<\/strong> <strong>iteration<\/strong> \u2014 we\u2019re not sure how many iterations we\u2019ll need \u2014 we cannot even establish an upper bound!<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h1><a id=\"_Toc519230997\"><\/a>Nested Loops<\/h1>\n<p class=\"import-Normal\">Just like with<code>if<\/code> statements, <code>while<\/code> and <code>for<\/code> blocks can contain arbitrary Python statements, including other loops. A loop can therefore be nested within another loop. To see how nested loops work, consider a program that prints out a multiplication times tables (<code>multiplication.py<\/code>).<\/p>\n<div class=\"textbox\">\n<p><code>#multiplcation tables<\/code><br \/>\n<code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">table = int(input(\"which multiplication times table do you want to<\/code><br \/>\nprint? (choose from 1 to 12) &#8220;))<br \/>\n<code style=\"padding-left: 30px\">x = table<\/code><br \/>\nexcept:<br \/>\n<code style=\"padding-left: 30px\">print(\"ERROR: enter a whole number\")<\/code><br \/>\nelse:<br \/>\n<code style=\"padding-left: 30px\">if table &gt; 0 and table &lt; 13:<\/code><br \/>\n<code style=\"padding-left: 60px\">for y in range(1, 13):<\/code><br \/>\n<code style=\"padding-left: 90px\">print (x,'*', y,'=', x*y)<\/code><br \/>\n<code style=\"padding-left: 30px\">else:<\/code><br \/>\n<code style=\"padding-left: 60px\">print (\"ERROR: multiplication tables can be generated from 1 to 12 only\")<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Let us examine more closely the code in this program.<\/p>\n<table>\n<tbody>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\">Python Statement<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\">Explanation<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>try:<\/code><\/p>\n<p class=\"import-Normal\"><code>table = int(input(\"which multiplication times table do you want to print? (choose from 1 to 12) \"))<\/code><\/p>\n<p class=\"import-Normal\"><code>x = table<\/code><\/p>\n<p class=\"import-Normal\"><code>except:<\/code><\/p>\n<p class=\"import-Normal\"><code>print(\"ERROR: enter a whole number\")<\/code><\/p>\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\n<p class=\"import-Normal\"><code>if table &gt; 0 and table &lt; 13:<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">We use the <code>try-except-else<\/code> block to catch the error of non-numeric input from the user.<\/p>\n<p class=\"import-Normal\">The <code>if<\/code> block following the <code>else<\/code> block assures that the user is entering a number in the correct range of <code>1<\/code> to <code>12<\/code>.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>for y in range(1, 13):<\/code><\/p>\n<p class=\"import-Normal\"><code>print (x,'*', y,'=', x*y)<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">The <code>for<\/code> loop is generating the multiplication times table requested from the user.The variable <code>x<\/code> represents the times-table the user requested and the variable <code>y<\/code> provides each entry in the times table. We use a loop to print the contents of each row. The outer loop controls how many total rows the program prints, and the inner loop, executed in its entirety each time the program prints a row, prints the individual elements that make up a row.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>print(\"Enter positive numbers to sum (entering a negative number ends the program).\")<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">This statement provides instructions for this app.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>else:<\/code><\/p>\n<p class=\"import-Normal\"><code>print (\"ERROR: multiplication tables can be generated from 1 to 12 only\")<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">This is the end of the program. This block, which prints and error message, only executes if the user did not enter a number in the correct range of 1 to 12.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"import-Normal\">Example output:<\/p>\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/multiplication.py<\/code><br \/>\n<code style=\"color: #0000ff\">which multiplication times table do you want to print? (choose from 1 to 12)<\/code><code>5<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 1 = 5<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 2 = 10<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 3 = 15<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 4 = 20<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 5 = 25<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 6 = 30<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 7 = 35<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 8 = 40<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 9 = 45<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 10 = 50<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 11 = 55<\/code><br \/>\n<code style=\"color: #0000ff\">5 * 12 = 60<\/code>&gt;&gt;&gt;<\/div>\n<p>Now let us consider adding to this program to generate all the multiplication times tables from 1 to 12. This is easily done with nested loops.<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>#multiplcation times tables tables<\/code><br \/>\n<code class=\"import-Normal\">for x in range(1, 13):<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">for y in range(1, 13):<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 60px\">print (x,'*', y,'=', x*y)<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">The output after execution of this 3-lines-of-code program generates 144 lines of output!<\/p>\n<div class=\"textbox\">\n<p class=\"import-Normal\"><code>1 * 1 = 11 * 2 = 21 * 3 = 31 * 4 = 41 * 5 = 51 * 6 = 61 * 7 = 71 * 8 = 81 * 9 = 91 * 10 = 101 * 11 = 111 * 12 = 122 * 1 = 22 * 2 = 42 * 3 = 62 * 4 = 82 * 5 = 102 * 6 = 122 * 7 = 142 * 8 = 162 * 9 = 182 * 10 = 202 * 11 = 222 * 12 = 24...12 * 1 = 1212 * 2 = 2412 * 3 = 3612 * 4 = 4812 * 5 = 6012 * 6 = 7212 * 7 = 8412 * 8 = 9612 * 9 = 10812 * 10 = 12012 * 11 = 13212 * 12 = 144<\/code><\/p>\n<\/div>\n<h1><a id=\"_Toc519230998\"><\/a>Basic File Processing<\/h1>\n<p class=\"import-Normal\">While a program is running, its data is stored in random access memory (RAM) on the computer it is execution on. RAM is fast and inexpensive, but it is also volatile, which means that when the program ends, or the computer shuts down, the data in RAM disappears. To make data available the next time the computer is turned on and the program is started, it has to be written to a non-volatile storage medium, as a file. By reading and writing files, programs can save information between program runs.<\/p>\n<p class=\"import-Normal\">So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.<\/p>\n<p class=\"import-Normal\">For our purposes, we will assume that our data files are text files\u2013that is, files filled with characters. The Python programs that you write are stored as text files as are any HTML webpage files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents. Note that text files have an End-Of-Line (EOL) character to indicate each line&#8217;s termination.<\/p>\n<h2><a id=\"_Toc519230999\"><\/a>Reading and Writing Text Files<\/h2>\n<p class=\"import-Normal\">In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. The following table shows the functions and methods that can be with files.<\/p>\n<table style=\"height: 278px\">\n<tbody>\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Function\/Method Name<\/strong><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Use<\/strong><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Explanation<\/strong><\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 59px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 167.625px\">\n<p class=\"import-Normal\">open<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 176.625px\">\n<p class=\"import-HTMLPreformatted\"><code>f1=open('workfile.txt','r')<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 835.625px\">\n<p class=\"import-Normal\">Open a file called <em>workfile.txt<\/em> and use it for reading. This will return a reference to a file object assigned to the variable <code>f1<\/code>.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 59px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 167.625px\">\n<p class=\"import-Normal\">open<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 176.625px\">\n<p class=\"import-HTMLPreformatted\"><code>f1= open('workfile.txt','w')<\/code><\/p>\n<p class=\"import-Normal\">\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 59px;width: 835.625px\">\n<p class=\"import-Normal\">Open a file called <em>workfile.txt<\/em> and use it for writing. This will also return a reference to a file object assigned to the variable <code>f1<\/code>.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\n<p class=\"import-Normal\">close<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\n<p class=\"import-Normal\"><code>f1.close()<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\n<p class=\"import-Normal\">When a file use is complete, the file must be closed. This will free up any system resources taken up by the open file.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\n<p class=\"import-Normal\">read<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\n<p class=\"import-HTMLPreformatted\"><code>data = f1.()<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\n<p class=\"import-Normal\">Read the entire contents of the file <code>f1<\/code> and assign it to the variable data.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 30px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 167.625px\">\n<p class=\"import-Normal\">write<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 176.625px\">\n<p class=\"import-Normal\"><code>f1.write(string)<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 30px;width: 835.625px\">\n<p class=\"import-Normal\">Write the contents of <em class=\"import-Emphasis\">string<\/em> to the file <code>f1<\/code>, returning the number of characters written.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\" style=\"height: 29px\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 167.625px\">\n<p class=\"import-Normal\">readline<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 176.625px\">\n<p class=\"import-Normal\"><code>data = f1.readline()<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt;border: 0.5pt solid windowtext;height: 29px;width: 835.625px\">\n<p class=\"import-Normal\">Read a single line from the file <code>f1<\/code>; a newline character (<code>\\n<\/code>) is left at the end of the string.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: center\"><small><a id=\"_Toc519003538\"><\/a><em>Table 7: File Functions and Methods<\/em><\/small><\/p>\n<p class=\"import-Normal\">Python file object attributes provide information about the file and file state. The following table shows how to identify some of the object&#8217;s attributes.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Attribute<\/strong><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Use<\/strong><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"vertical-align: middle;padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\" style=\"text-align: center\"><strong>Explanation<\/strong><\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">file.closed<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>print(\"Closed or not : \", file1.closed)<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">Returns true if <code>file1<\/code> is closed, false otherwise.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">file.mode<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>print(\"Opening mode : \", file1.mode)<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">Returns access mode with which <code>file1<\/code> was opened.<\/p>\n<\/td>\n<\/tr>\n<tr class=\"TableGrid-R\">\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">file.name<\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\"><code>print(\"Name of the file: \", file1.name)<\/code><\/p>\n<\/td>\n<td class=\"TableGrid-C\" style=\"padding: 0pt 5.4pt 0pt 5.4pt;border: solid windowtext 0.5pt\">\n<p class=\"import-Normal\">Returns name of <code>file1<\/code>.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: center\"><em><small>Table 8: File Object Attributes<\/small><\/em><\/p>\n<p class=\"import-Normal\">The statement<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file1 = open('myfile.txt', 'r')<\/code><\/p>\n<p class=\"import-Normal\">creates and returns a file object in the variable named <code>file1<\/code>. The first argument to open is the name of the file, and the second argument is a mode (in this example the mode is to read the file). This statement will attempt to read the content of the text file named <code>myfile.txt<\/code>. If the file does not exist or the user of the program does not have adequate permissions to open the file, the <code>open<\/code> function will raise an exception.<\/p>\n<div class=\"textbox\">\n<p><code>try:<\/code><\/p>\n<p style=\"padding-left: 30px\"><code>file1 = open('myfile.txt', 'r')<\/code><\/p>\n<p><code>except:<\/code><\/p>\n<p style=\"padding-left: 30px\"><code>print(\u201cERROR: unable to open or locate the file\u201d)<\/code><\/p>\n<p><code># Do other kinds of processing here...<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Similar to handling an error of invalid user input we need to use the <code>try-except-else<\/code> block to handle trying to read from a file which does not exist The following is an example:<\/p>\n<p class=\"import-Normal\">The statement<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2 = open('myfile.txt', 'w')<\/code><\/p>\n<p class=\"import-Normal\">creates and returns a file object in the variable named <code>file2<\/code> which will write data to the text file named <code>myfile.txt<\/code>. If the file does not exist, the function creates the file on disk; no exceptions are raised when writing to a file. If a file by that name currently exists, new data will replace the current data stored in the file. This means any pre-existing data in the file will be lost.<\/p>\n<p class=\"import-Normal\">Once you have a file object capable of writing (opened with &#8216;w&#8217;) you can save data to the file associated with that file object using the write method. For a file object named <code>file2<\/code>, the statement<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data')<\/code><\/p>\n<p class=\"import-Normal\">stores the string &#8216;data&#8217; to the file. The three statements<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data')<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('compute')<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('process')<\/code><\/p>\n<p class=\"import-Normal\">writes the text <code>'datacomputeprocess'<\/code> to the file. If our intention is to retrieve the three separate original strings, we must add delimiters to separate the pieces of data. Newline characters serve as good delimiters:<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('data\\n')<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('compute\\n')<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>file2.write('process\\n')<\/code><\/p>\n<p class=\"import-Normal\">This places each word on its own line in the text file. The advantage of storing each piece of data on its own line of text is that it makes it easier to read the data from the file with a <code>for<\/code> statement. If <code>file2<\/code> is a file object created for reading, the following code:<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>for line in file2:<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>print(line.strip())<\/code><\/p>\n<p class=\"import-Normal\">reads in each line of text from the file and prints it out. The variable <code>line<\/code> is a string, and we use the <code>strip<\/code> method to remove the trailing newline (<code>'\\n'<\/code>) character.<\/p>\n<p class=\"import-Normal\">We also can read the contents of the entire file into a single string using the file object\u2019s read method:<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>contents = file2.read()<\/code><\/p>\n<p class=\"import-Normal\">Given the text file from above, the code<\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>in = open('compterms.txt', 'r')<\/code><\/p>\n<p class=\"import-Normal\" style=\"margin-left: 36pt\"><code>str = in.read()<\/code><\/p>\n<p class=\"import-Normal\">assigns to <code>str<\/code> the string <code>'data\\ncompute\\nprocess\\n'<\/code>.<\/p>\n<p class=\"import-Normal\">The <code>open<\/code> method opens a file for reading or writing, and the <code>read<\/code>, <code>write<\/code>, and other such methods enable the program to interact with the file. When the executing program is finished with its file processing it must call the <code>close<\/code> method to close the file properly. Failure to close a file can have serious consequences when writing to a file, as data meant to be saved could be lost. Every call to the open function should have a corresponding call to the file object\u2019s <code>close<\/code> method.<\/p>\n<h2 class=\"import-Normal\"><span class=\"import-Heading3Char\">Practice<\/span> &#8211; Following are two simple programs designed to write data to a file and then read and print each line of a file. Try entering, saving and running the following programs (<code>writeFile.py<\/code> and <code>readFile.py<\/code>).<\/h2>\n<div class=\"textbox\"><code>file1 = open(\"compterms.txt\", 'w') #Create a file to write to<\/code><br \/>\n<code># write data to the opened file<\/code><br \/>\n<code>file1.write('data\\n')<\/code><br \/>\n<code>file1.write('compute\\n')<\/code><br \/>\n<code>file1.write('process\\n')<\/code><br \/>\n<code>file1.write('file format\\n')<\/code><br \/>\n<code>file1.write('gigabyte\\n')<\/code><br \/>\n<code>file1.close() # Close the file after processing data<\/code><\/div>\n<p class=\"import-Normal\" style=\"text-align: center\"><em>Figure 49: writeFile.py<\/em><\/p>\n<p class=\"import-Normal\">Figure 50: readFile.py<\/p>\n<div class=\"textbox\"><span class=\"import-Normal\">try:<br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">file1 = open('compterms.txt','r') # try to find &amp; open the file<\/code><br \/>\n<code class=\"import-Normal\">except:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code><br \/>\n<code class=\"import-Normal\">else:<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 60px\">print(line.strip()) # Remove trailing newline character and print the line<\/code><br \/>\n<code class=\"import-Normal\" style=\"padding-left: 30px\">file1.close() # Close the file after processing data<br \/>\n<\/code><\/span><\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">This is the output after running this program:<\/p>\n<div class=\"textbox\">RESTART: C:\/Users\/lh166266.UALBANY\/Code\/readFile.py<br \/>\n<code style=\"color: #0000ff\">data<\/code><br \/>\n<code style=\"color: #0000ff\">compute<\/code><br \/>\n<code style=\"color: #0000ff\">process<\/code><br \/>\n<code style=\"color: #0000ff\">file format<\/code><br \/>\n<code style=\"color: #0000ff\">gigabyte<\/code><br \/>\n&gt;&gt;&gt;<\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">We can also read and process each line of data in a file by using the <code>readline()<\/code> method. Try entering, saving and running the following programs <code>(readFile2.py)<\/code>. The output is the same.<\/p>\n<div class=\"textbox\">\n<p><code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">file1 = open('compterms.txt','r') # try to find &amp; open the file<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">line = file1.readline() # Read the first line<\/code><br \/>\n<code style=\"padding-left: 30px\">while line: # Enter the loop as long as there is a line of<\/code><br \/>\n<code>data to read<\/code><br \/>\n<code style=\"padding-left: 30px\">print(line.strip()) # Remove trailing newline character and print the line<\/code><br \/>\n<code style=\"padding-left: 30px\">line = file1.readline() # Read the next line<\/code><br \/>\n<code>file1.close() # Close the file after processing data<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h2><a id=\"_Toc519231001\"><\/a>Processing \u201cBig Data\u201d<\/h2>\n<p class=\"import-Normal\">Big data is large, and often times complex, data sets that need to be processed into useful information. Python has emerged over the past few years as a leader in data science programming including the analysis and visualization of large data sets.<\/p>\n<p class=\"import-Normal\">Data sets grow rapidly &#8211; in part because they are increasingly gathered by cheap and numerous information-sensing internet of things devices such as mobile devices, aerial (remote sensing), software logs, cameras, microphones, radio-frequency identification (RFID) readers and wireless sensor networks. The world&#8217;s technological per-capita capacity to store information has roughly doubled every 40 months since the 1980s; as of 2012, every day 2.5 exabytes (2.5\u00d71018) of data are generated. Based on an IDC (International Data Corporation) report prediction, the global data volume will grow exponentially from 4.4 zettabytes to 44 zettabytes between 2013 and 2020. By 2025, IDC predicts there will be 163 zettabytes of data.<sup class=\"import-FootnoteReference\"><a class=\"footnote\" title=\"Wikipedia contributors. &quot;Big data.&quot; Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 4 Jul. 2018. Web. 12 Jul. 2018.\" id=\"return-footnote-76-1\" href=\"#footnote-76-1\" aria-label=\"Footnote 1\"><sup class=\"footnote\">[1]<\/sup><\/a><\/sup><\/p>\n<div style=\"width: 277px\" class=\"wp-caption alignright\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161443\/image49.jpg\" alt=\"image\" width=\"267\" height=\"189\" \/><\/p>\n<p class=\"wp-caption-text\">Figure 51: \u201cData Information\u201d(www.maxpixel.net\/Circle-Know-Arrangement-Data-Information-Learn-229113)\u00a0is licensed under <a href=\"https:\/\/creativecommons.org\/share-your-work\/public-domain\/cc0\/\">CC-BY 0<\/a><\/p>\n<\/div>\n<p class=\"import-Normal\">An example of a successful business that uses python for collecting and analyzing data is ForecastWatch. ForecastWatch.com is in the business of rating the accuracy of weather reports from companies such as Accuweather, MyForecast.com, and The Weather Channel. Over 36,000 weather forecasts are collected every day for over 800 U.S. cities, and later compared with actual climatological data. These comparisons are used by meteorologists to improve their weather forecasts, and to compare their forecasts with others. They are also used by consumers to better understand the probable accuracy of a forecast.<sup class=\"import-FootnoteReference\"><a class=\"footnote\" title=\"Python Software Foundation. Python Success Stories, https:\/\/www.python.org\/about\/success\/forecastwatch\/. Accessed July 12, 2018\" id=\"return-footnote-76-2\" href=\"#footnote-76-2\" aria-label=\"Footnote 2\"><sup class=\"footnote\">[2]<\/sup><\/a><\/sup><\/p>\n<p class=\"import-Normal\">We will use real data from open source data sets (that is saved as text files) for programming practice.<\/p>\n<h2><a id=\"_Toc519231002\"><\/a>Practice<\/h2>\n<p class=\"import-Normal\"><strong>Problem Statement<\/strong>: Using the text file, <code>NYScoastalFlooding.txt<\/code>, identify each of the New York State counties (zones) effected by coastal flooding during the month of August within the dataset provided.<\/p>\n<p class=\"import-Normal\">The first step in finding a solution for this problem is to review and understand the format of the data set provided. Open the text in a text editor and note the field headings in the first line of the file. The following is a small sample from the <code>NYScoastalFlooding.txt<\/code> file.<\/p>\n<div class=\"textbox\"><code>YEAR, MONTH_NAME, EVENT_TYPE, CZ_TYPE,CZ_FIPS, CZ_NAME<\/code><br \/>\n<code>2017, March, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code><br \/>\n<code>2017, March, Coastal Flood, Z, 179, SOUTHERN NASSAU<\/code><br \/>\n<code>2017, March, Coastal Flood, Z, 71, SOUTHERN WESTCHESTER<\/code><br \/>\n<code>2017, March, Coastal Flood, Z, 81, SOUTHEAST SUFFOLK<\/code><br \/>\n<code>2017, October, Coastal Flood, Z, 3, MONROE<\/code><br \/>\n<code>2017, October, Coastal Flood, Z, 5, NORTHERN CAYUGA<\/code><br \/>\n<code>2017, October, Coastal Flood, Z, 4, WAYNE<\/code><br \/>\n<code>2017, October, Coastal Flood, Z, 6, OSWEGO<\/code><br \/>\n<code>2017, January, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code><br \/>\n<code>2017, October, Coastal Flood, Z, 1, NIAGARA<\/code><br \/>\n<code>2017, January, Coastal Flood, Z, 179, SOUTHERN NASSAU<\/code><\/div>\n<p class=\"import-Normal\">We see that the data set has six fields:<\/p>\n<ol>\n<li>year: Four digit year for the event in this record<\/li>\n<li>month_name: Name of the month for the event in this record (spelled out; not abbreviated)<\/li>\n<li>event_type spelled out; not abbreviated<\/li>\n<li>cz_type: Indicates whether the event happened in a (C) county\/parish, (Z) zone or (M) marine<\/li>\n<li>cz_fips: The county FIPS number is a unique number assigned to the county by the National Institute for Standards and Technology (NIST) or NWS Forecast Zone Number<\/li>\n<li>cz_name: County\/Parish, Zone or Marine Name assigned to the county FIPS number or NWS Forecast Zone<\/li>\n<\/ol>\n<p class=\"import-Normal\">We also notice that all but the first field on each line has a blank space before it (this is important!).<\/p>\n<p>We will break this problem into smaller pieces. Let us start with a program that reads each of the records and keeps a count of the number of records in the file (dataRecordNumb.py). This program is a modification of our readFile.py program.<\/p>\n<div class=\"textbox\">\n<p><code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">file1 = open('NYScoastalFlooding.txt ','r') # try to find &amp; open the file<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">count = 0 # Initialize recount cout to zero<\/code><br \/>\n<code style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code><br \/>\n<code style=\"padding-left: 60px\">print(line.strip()) # Print the record<\/code><br \/>\n<code style=\"padding-left: 60px\">count = count + 1 # increment record counter<\/code><br \/>\n<code style=\"padding-left: 30px\">print(\"There are\",count,\"data records in this file\")<\/code><br \/>\n<code style=\"padding-left: 30px\">file1.close() # Close the file after processing data<\/code><\/p>\n<\/div>\n<p class=\"import-Normal\">The last line of the output from running this program:<\/p>\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/dataRecordNumb.py<\/code><br \/>\n<code style=\"color: #0000ff\">There are 61 data records in this file<\/code><br \/>\n<code>&gt;&gt;&gt;<\/code><\/div>\n<p>&nbsp;<\/p>\n<p class=\"import-Normal\">Recall from Unit 2 when we used the <code>split()<\/code> method to identify each individual word in a sentence. What the method does is split or breakup a string and add the data to a list of separate \u2018chunks\u2019 using a defined separator. So if this line is read<\/p>\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>2017, January, Coastal Flood, Z, 79, NORTHEAST SUFFOLK<\/code><\/p>\n<p class=\"import-Normal\">and we split the line into individual fields we could identify those records effected by coastal flooding during the month of August.<\/p>\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>fields = line.split(\u2018,\u2019)<\/code><\/p>\n<p class=\"import-Normal\">If we now print fields we have a list of all the fields which we can now access.<\/p>\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>&gt;&gt;&gt; print(fields)<\/code><\/p>\n<p class=\"import-Normal\" style=\"text-indent: 36pt\"><code>['2017', ' January', ' Coastal Flood', ' Z', ' 79', ' NORTHEAST SUFFOLK']<\/code><\/p>\n<p class=\"import-Normal\">Notice the extra blank space before the string \u201cJanuary\u201d in the list <code>fields<\/code>. When trying to identify those records with the string \u201cAugust\u201d the extra space must be dealt with!<\/p>\n<p>Let us complete the second program to solve the problem of identifying (and print) each of the New York State counties (zones) effected by coastal flooding during the month of August (<code>NYScountiesAug.py<\/code>).<\/p>\n<div class=\"textbox\">\n<p><code># identify each of the New York State counties (zones) effected by coastal flooding during the month of August<\/code><br \/>\n<code>print(\"The following are the NYS counties (zones) effected by coastal flooding during the month of August:\")<\/code><br \/>\n<code>try:<\/code><br \/>\n<code style=\"padding-left: 30px\">file1 = open('NYScoastalFlooding.txt ','r') # try to find &amp; open the file<\/code><br \/>\n<code>except:<\/code><br \/>\n<code style=\"padding-left: 30px\">print('ERROR: unable to open or locate the file')<\/code><br \/>\n<code>else:<\/code><br \/>\n<code style=\"padding-left: 30px\">for line in file1: # Read each line as text<\/code><br \/>\n<code style=\"padding-left: 60px\">fields = line.split(\",\") # split each line into a list of 'fields'<\/code><br \/>\n<code style=\"padding-left: 60px\">if fields[1] == \" August\": # check if the 2nd field is August<\/code><br \/>\n<code style=\"padding-left: 90px\">county = fields[5] # identify the county from the 6th field<\/code><br \/>\n<code style=\"padding-left: 90px\">print(county.strip()) # Print the record<\/code><br \/>\n<code style=\"padding-left: 30px\">file1.close() # Close the file after processing data<\/code><\/p>\n<\/div>\n<p>The output from running this program:<\/p>\n<div class=\"textbox\"><code>RESTART: C:\/Users\/lh166266.UALBANY\/Code\/NYScountiesAug.py<\/code><br \/>\n<code style=\"color: #0000ff\">The following are the NYS counties (zones) <\/code><code>effected<\/code><code style=\"color: #0000ff\"> by coastal flooding during the month of August:<\/code><br \/>\n<code style=\"color: #0000ff\">OSWEGO<\/code><br \/>\n<code style=\"color: #0000ff\">NIAGARA<\/code><br \/>\n<code style=\"color: #0000ff\">NORTHERN CAYUGA<\/code><br \/>\n<code style=\"color: #0000ff\">JEFFERSON<\/code><br \/>\n<code style=\"color: #0000ff\">ORLEANS<\/code><br \/>\n<code style=\"color: #0000ff\">MONROE<\/code><br \/>\n<code style=\"color: #0000ff\">WAYNE<\/code><br \/>\n&gt;&gt;&gt;<\/div>\n<p class=\"import-Normal\">To test if the program correctly identified all records effected by coastal flooding during the month of August you would need to manually go through each of the 61 records and flag the records that should be found and printed (or use an app such as Excel to do a sort and count for you).<\/p>\n<p class=\"import-Normal\">The actual data set I downloaded had a total of 56,921 records and 51 different fields (a lot more data than what we just worked with!). A professional data scientist would also test her program using a subset of the large data set until she could be satisfied that the program was running correctly and producing the correct results.<\/p>\n<h1><a id=\"_Toc519231003\"><\/a>Unit Summary<\/h1>\n<p class=\"import-Normal\">TBD<\/p>\n<ul>\n<li>Read and write programs using the Python IF and IF\/ELIF\/ELSE statements to implement a simple decision structures.<\/li>\n<li>Write simple exception handling code to catch simple Python run-time errors.<\/li>\n<li>Read and write programs using the Python FOR and WHILE statements to implement a simple loop structures.<\/li>\n<li>Construct and implement algorithms that use decision and loop structures.<\/li>\n<li>Apply basic file processing concepts and techniques for reading and writing text files in Python.<\/li>\n<\/ul>\n<h1><a id=\"_Toc519231004\"><\/a>Practice Problems<\/h1>\n<ol>\n<li>Write a program to accept a number from the user and print whether it is positive or negative.<\/li>\n<li>Accept three numbers from the user and print the greatest number.<\/li>\n<li>Write a program that accepts a number in the range from 1 to 7 from the user and generates and displays the name of the weekday.<\/li>\n<li>Write a program to input 5 numbers from the user and calculates and displays their sum and average.<\/li>\n<li>Write a program that accepts an integer number and indicates whether it is negative, zero, or positive. Force the user to enter only valid data (repeatedly ask the user to enter only an integer number)<\/li>\n<li>Provide the exact sequence of integers specified by each of the following range expressions.\n<ol type=\"a\">\n<li>range(5)<\/li>\n<li>range(5, 10)<\/li>\n<li>range(5, 20, 3)<\/li>\n<li>range(20, 5, -1)<\/li>\n<li>range(20, 5, -3)<\/li>\n<li>range(10, 5)<\/li>\n<li>range(0)<\/li>\n<li>range(10, 101, 10)<\/li>\n<li>range(10, -1, -1)<\/li>\n<li>range(-3, 4)<\/li>\n<li>range(0, 10, 1)<\/li>\n<\/ol>\n<\/li>\n<li>Write a program to print a pattern like a right angle triangle with numbers where each number will repeat in a row. The pattern is as follows:<br \/>\n1<br \/>\n22<br \/>\n333<br \/>\n4444<br \/>\n55555<\/li>\n<li>Write a program to print a pattern like a pyramid with numbers where each number will repeat in a row. The pattern is as follows:<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-117\" style=\"text-align: initial;font-size: 1em\" src=\"https:\/\/s3-us-west-2.amazonaws.com\/courses-images\/wp-content\/uploads\/sites\/3454\/2018\/07\/23161444\/Screen-Shot-2018-07-18-at-3.28.16-PM.png\" alt=\"\" width=\"156\" height=\"115\" \/><\/li>\n<li>Find a poem you like and save it as a text file named poem.txt. Write a program that counts the number of lines in your program. Print out the line count and each individual line in the program (no extra blank lines!)<\/li>\n<li>Write a program that stores the first 100 integers to a text file named numbers.txt. Each number should appear on a line all by itself.<\/li>\n<li>Write a program to find the longest word in a text file.<\/li>\n<\/ol>\n<div id=\"sdfootnote21sym\">\u2026<\/div>\n<div id=\"sdfootnote22sym\">\u2026<\/div>\n<hr class=\"before-footnotes clear\" \/><div class=\"footnotes\"><ol><li id=\"footnote-76-1\">Wikipedia contributors. \"Big data.\" Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 4 Jul. 2018. Web. 12 Jul. 2018. <a href=\"#return-footnote-76-1\" class=\"return-footnote\" aria-label=\"Return to footnote 1\">&crarr;<\/a><\/li><li id=\"footnote-76-2\">Python Software Foundation. Python Success Stories, https:\/\/www.python.org\/about\/success\/forecastwatch\/. Accessed July 12, 2018 <a href=\"#return-footnote-76-2\" class=\"return-footnote\" aria-label=\"Return to footnote 2\">&crarr;<\/a><\/li><\/ol><\/div>","protected":false},"author":23485,"menu_order":4,"template":"","meta":{"_candela_citation":"[]","CANDELA_OUTCOMES_GUID":"","pb_show_title":"on","pb_short_title":"","pb_subtitle":"","pb_authors":[],"pb_section_license":""},"chapter-type":[48],"contributor":[],"license":[],"class_list":["post-76","chapter","type-chapter","status-publish","hentry","chapter-type-numberless"],"part":22,"_links":{"self":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapters\/76","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapters"}],"about":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/wp\/v2\/types\/chapter"}],"author":[{"embeddable":true,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/wp\/v2\/users\/23485"}],"version-history":[{"count":42,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapters\/76\/revisions"}],"predecessor-version":[{"id":292,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapters\/76\/revisions\/292"}],"part":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/parts\/22"}],"metadata":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapters\/76\/metadata\/"}],"wp:attachment":[{"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/wp\/v2\/media?parent=76"}],"wp:term":[{"taxonomy":"chapter-type","embeddable":true,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/pressbooks\/v2\/chapter-type?post=76"},{"taxonomy":"contributor","embeddable":true,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/wp\/v2\/contributor?post=76"},{"taxonomy":"license","embeddable":true,"href":"https:\/\/courses.lumenlearning.com\/suny-albany-programmingforproblemsolving\/wp-json\/wp\/v2\/license?post=76"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}