--- slideOptions: theme: white --- # Chapter 5 - Loops --- ###### tags: `Computer programming` ## Learning objectives By the end of this chapter, you should able to: 1. Use `while` loop to repeat an operation or a series of operation until the condition is met 2. Use `for` loop to repeat an operation with given number of times 3. Rewrite `for` loop with `while` statement 4. Describe the algorithms for data verification --- ## Introduction Sometimes, we need to do an action or a series of actions many times **repeatedly** until a condition is met. We called that a loop. There are two types of loops in programming, i.e. the *event-controlled loops* and *counter-controlled loops*. * **Event-controlled loops**: repeat the action(s) until the *given condition is met* * **Counter-countered loops**: repeat the action(s) for a *known number of times* --- Besides, there is another method to categorise the loops, as shown below. * **Pretest loop**: check the condition before the action(s) * **Posttest loop**: execute the action(s) first and then check the condition --- ![](https://i.imgur.com/Xf6b0Jw.png) --- ## Loops in Python In Python, there are two types of loops and they are listed below. `while`: Event-controlled loop, Pretest loop `for`: Counter-controlled loop, Pretest loop The posttest loop is not implemented in Python. --- ## `while` loop The `while` loop is a pretest loop in Python, that will perform the action when the value of condition expression is `True`. The `while` statement has a similar syntax to `if` statement, as shown below. --- ![](https://i.imgur.com/MlFf012.png) --- ### Application - data validation We can use a `while` statement to verify the input value within a specific range. Below shows an example using a `while` statement to check whether the user input is a positive integer or not. --- ```python!= num = 0 while num <= 0: num = int(input("Please input a positive integer: ")) print("The integer is", num) ``` <iframe src="https://trinket.io/embed/python3/d9dbaf73ca?runOption=run&start=result" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ## `for` loop A `for` loop is the counter-controlled loop in Python, that can be executed the loop body for a known number of times. Before we jump into the further discussion of `for` loop, we need to understand the range function first. --- ### The `range` function We usually use the range function to generate a sequence of numbers. For example, we use `range(5)` to generate a range of 0, 1, 2, 3, 4 (totally 5 numbers). We can read the sequence by converting it into an explicit list by `list` function. --- ```python!= print(list(range(5))) ``` <iframe src="https://trinket.io/embed/python3/f2b0197c29?runOption=run&start=result" width="100%" height="100" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- We can adjust the starting number, stopping number and the step of the `range`. The general form of range and its description is shown below. ```python! range(start=0, stop, step=1) ``` | Parameter | Description | |---|---| | `start` | *Optional*. An integer number specifying at which position to start. Defalut is 0. | | `stop` | *Required*. An integer number specifying at which position to stop (not included). | | `step` | *Optional*. An integer number (including negative numbers) specifying the incrementation. Default is 1. | --- Below shows some examples. ```python!= print(list(range(5))) print(list(range(3, 6))) print(list(range(3, 8, 2))) print(list(range(8, 4, -1))) print(list(range(10, 0, -3))) ``` <iframe src="https://trinket.io/embed/python3/e027a2bb18?runOption=run&start=result" width="100%" height="160" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ### The `for` statement The following shows the general form of `for` statment. ```python! for variabel in sequence: ``` --- The variable after the keyword for is called the *loop index*. It takes on each successive value in the sequence, and then statements in the body are executed once for each value. The sequence portion consists of a *list* of values (list would be discussed in a later chapter). Here are some examples of using the list. --- ```python!= for i in [0, 1, 2, 3]: print(i) ``` <iframe src="https://trinket.io/embed/python3/497ddb2173?runOption=run&start=result" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ```python!= for even in [4, 16, 36, 64]: print(even) ``` <iframe src="https://trinket.io/embed/python3/3b64ec2175?runOption=run&start=result" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- We normally use the sequence generated by the range function in the `for` statement. ```python!= for i in range(5): print(i) ``` <iframe src="https://trinket.io/embed/python3/c21097d58f?runOption=run&start=result" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- Below shows an example on using the nested `for` loop to draw a number triangle. ```python!= limit = int(input("Enter a number between 1 and 9: ")) # limit should be reached, so the maximum number need to +1 for line in range(limit + 1): for num in range(line): print(num + 1, end="") print("") ``` --- <iframe src="https://trinket.io/embed/python3/02e5a66534?runOption=run&start=result" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> --- ### Relationship between `while` loop and `for` loop Actually we can use a `while` statment to perform a counter-controlled loop. However, the `for` statement is suggested to increase the code readability. --- The following program fragments are equivalent to calculating the sum of 10 number that are iput by the user. ![](https://i.imgur.com/yEVCfSQ.png) --- ## Data validation *Data validation* is a data entry check that only checks if the data if *valid*, in other words, it is sensible. It does not mean that the data is actually correct. There are several kinds of data validation methods, as shown below. --- | Name | Descrption | | --- | --- | | Range checks | These are used with numeric fields to limit the range of numbers a user can enter. For example, a typical range-check validation rule might be >= 13 and <= 20.| | Format checks |These only allow valid text of numbers. Many use input ‘masks’ such as **000LLL**. Such a mask would only allow 3 numbers followed by 3 letters. | | Member list | This method of validation is used to *limit entries* to those that are members of a list of a list of allowed entries. The choice may appear in a *drop-down* list to reduce transcription errors or be in the form of a list of acceptable entries that the input is checked against. | | Check digits | An extra ‘check digit’ is calculated from the numbers to be entered and added to the end. This would be discussed more in the later topic. | | Presence check | Simply check that an entry has been made in a particular field. It has not then the system will not allow the record to be saved or any entries to be made in later fields. | --- The above data validation methods can be done by loops in programming. For *check digits*, it requires the use of arrays and lists, that would be discussed later. --- ## Chapter summary * A Python `while` statement is an example of an indefinte loop. It continues to iterate as long as the loop conditon remains `True`. * Definite loops are loops that execute a known number of times. The Python `for` loop is a definite loop that iterates through a sequence of values. A Python list is often in a `for` loop to provide a sequence of values for the loop --- * One important use of a for statement is in implementing a counter loop, which is a loop designed specifically for the purpose of repeating some portion of the program a specific number of times. A counted loop in Python is created by using the built-in range function to produce a suitably sized sequence of numbers. * Data validation means to check the validity of data input by user. --- ## Exercise 1. A Python while implements a definite loop. A. True B. False 2. The counted loop pattern uses a definite loop. A. True B. False --- 3. A while is a post-test loop. A. True B. False 4. A counted loop is designed to iterate a specific number of times. A. True B. False --- 5. A loop structure that test the loop condition after executing the loop body is called a A. pretest loop B. loop and a half C. sentinel loop D. posttest loop --- ## Programming Exercise ### Exercise 1 Rewrite Ch. 4 Ex 1 with `while` loop. This program is a simple guessing game. The computer generates a random number (integer) between 1 and 20. The user is given **at most four** tries to guess the exact number. After each guess, the program narrows down the range of the number. If the user gives the right guess, no more guesses should be made. If the user hasn't guessed the number after five tries, display the number with a message that the user should know it by now and terminate the game. --- **A possible successful dialog:** ```! I am thinking of a number between 1 and 20. Can you guess what it is? 10 The number is between 11 and 20. Try again: 15 The number is between 11 and 14. Try again: 12 Congratulations! You did it. The number was 12. ``` --- **A possible unsuccessful dialog** ```! I am thinking of a number between 1 and 20. Can you guess what it is? 10 The number is between 1 and 9. Try again: 5 The number is between 6 and 9. Try again: 7 The number is between 8 and 9. Try again: 9 Sorry. The number was 8. You should have gotten it by now. Better luck next time ``` --- _Hint: Use the following program to start with_ ```python! import random min = 1 max = 20 random_num = random.randint(min, max) ``` --- ### Exercise 2 Write a program that reads a list of positive integers (>0) and prints some statistics about the list of integers * The maximum integer and the number of times that integer appears. * The minimum integer and the number of times that integer appears. * The number of integers entered. * How many odd and even integers. * The sum of the integers. * The average of the integers The user needs to enter 0 at the end to complete the list and this zero is NOT counted as one of the integers. (You can assume that the user would not enter negative numbers.) Example: ``` Enter the integers: 5 Enter the integers: 2 Enter the integers: 15 Enter the integers: 3 Enter the integers: 7 Enter the integers: 15 Enter the integers: 8 Enter the integers: 9 Enter the integers: 5 Enter the integers: 2 Enter the integers: 15 Enter the integers: 3 Enter the integers: 7 Enter the integers: 0 The maximum is 15 and it appears 3 times. The minimum is 2 and it appears 2 times. 13 numbers are entered 10 are odd integers and 3 are even integers The sum is 96 The average is 7.38 ``` --- ### Exercise 3 Write a program that prints a diamond using an input character and a width which should be an odd integer. Example: ``` Enter a character: * Enter the width: 11 * *** ***** ******* ********* *********** ********* ******* ***** *** * ``` --- ### Exercsie 4 Write a program that prints a calendar month showing the seven days of a week. The user needs to enter the starting day of the week for the month and the number of days of the month. Example: ``` Enter the starting day of the week (0 for Sunday): 2 Enter the number of days of the month: 29 Sun Mon Tue Wed Thu Fri Sat --- --- --- --- --- --- --- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 --- --- --- --- --- --- --- ``` --- ### Exercise 5 The Fibonacci sequence starts 1, 1, 2, 3, 5, 8, …. Each number in the sequence (after the first two) is the sum of the previous two. Write a program that computes and output the *n*th Fibonacci number, where *n* is a value entered by the user. --- ### Exercise 6 A positive whole number $n > 2$ is prime if no number between 2 and $\sqrt{n}$ (inclusive) evenly divides $n$. Write a program that accepts a value of n as input and determines if the value is prime. ### Exercise 7 Modify the program in exercise 6 to find every prime number less than or equal to *n*.