CMIS 102 Looping, or iteration, or repetition as it is also known. It's the most important of the control constructs to control the flow of execution. A while loop executes a body of statements any number of times. The body is executed repeatedly, as long as the condition is True. In other words, "while" the condition is True, execute the statements of the body. An execution of a body is called an iteration. To iterate means to repeat. The while statement can be contrasted with the if statement that executes a body zero or once. Like an if, the while statement has a condition that controls it. The condition is exactly the same as the conditions used in if statements. So everything you learned about conditions, relational operators, logical operators, boolean values etc applies to the while statement. The syntax of a while statement is similar to that of an if statement. The only difference is the use of 'while' instead of 'if': while condition: statement(s) The condition is a boolean/logical expression, i.e. something that is True or False, just like the if. The semantics of the while differs from that of the if. When executed, the condition is evaluated, if it's True, the statements of the body are executed and then control automatically loops back up to the condition again and reevaluates it and if it's true the statements of the body are executed and then control automatically loops back up to the condition again and reevaluates it and if it's true the statements of the body are executed and then ... (I can cut and paste some more times if you'd like but I think you get the point). So what stops it? When the condition is False, the body is not executed (it's skipped), the while is finished and the program goes on to whatever is after the while (and its body). It's called a "while" statement because that's how it works. "While" the condition is True, do another iteration. Or, in other words, "as long as" the condition is True, repeat. Or, in reverse logic, "until" the condition is False, iterate. Loop back or cyclic nature of the while loop. This happens automatically, it's how the while statement functions. Something that eventually happens in the body will make the condition False. Maybe the condition depends on some user input value (e.g. loop inputting numbers from user until user enters a zero), or it could loop until all data has been input from a file, or until some combination of events have occurred. All the statements of the body are executed during an iteration (or a pass through it). So don't think that as soon as a statement that would make the condition False is executed that the loop terminates. It's only when the condition is evaluated at the top of the loop, after all the statements of the body have executed, that the loop will exit. A loop lets us process any amount of data. Without loop(s) we can only process a finite number of datums; with loop(s) we can do an infinite number of datums (theoretically). Here are some examples of while loops: #read numbers from user, output the square root. 0 to quit. #first number user enters "primes" the while condition num = eval(input("Enter nos. for sqr. rooting. 0 to quit: ")) while num != 0: #until number entered is a 0 print("SQRT is:", math.sqrt(num)) num = eval(input("Enter another no. for sqr. rooting. 0 to quit: ")) A particular value used to indicate the end of input is called a "sentinel". ------------------------------------------------------- #same, but check for negative numbers to avoid error of trying to do sqrt of negative number num = eval(input("Enter nos. for sqr. rooting. 0 to quit: ")) while num != 0: #until number entered is a 0 if num > 0: #body of any statement can contain any statements print("SQRT is:", math.sqrt(num)) else: print("No square root of negative number!") num = eval(input("Enter another no. for sqr. rooting. 0 to quit: ")) ------------------------------------ #input numbers from user. Negative number indicates end. sum = 0 num = eval(input("Enter a number: ")) #first number from user while num >= 0: #until a negative number is entered sum += num num = eval(input("Enter a number: ")) print("Sum is", sum) #if the first number entered is negative, the condition is False the #first time in the while statement, thus the body wouldn't be #executed even once A while loop will execute 0 or more times. Many while loops have this pattern: priming read of first datum while valid datum process the datum get next datum ---------------------------------------- #determine the number of digits in an integer #Ex. 548 has 3 digits, 2974 has 4 digits num = eval(input("Enter an integer: ")) digits = 0 while num > 0: num = num // 10 #integer divide by 10 digits += 1 print("Number of digits is",digits) Trace this code with some examples. Show the values of the variables that result from the execution of each statement. Does it work with a negative number? How to correct it? What about 0? ---------------------------------------- #read characters one per line until #, #count numbers of lowercase letters and of uppercase letters and of all other chars lowers = 0 uppers = 0 others = 0 c = input("Enter a character: ") while c != '#': #until # is entered if c.islower(): #c is one of 3 categories lowers += 1 elif c.isupper(): uppers += 1 else: others += 1 c = input("Enter a character: ") print("Number of lower letters:", lowers) print("Number of upper letters:", uppers) print("Number of all other chars:", others) -------------------------------------------------------------- What happens if the condition is always True? That's called an "infinite loop", because it will loop forever (or until the program is terminated somehow by the user or operating system, or, if you run it long enough, the electronics malfunctions). Infinite loops are usually a bug to be avoided. while True: #deliberate infinite loop. True is always true. s = input("Enter something") print(s) Ctrl-C [hold Ctrl and press c] will usually terminate a running (runaway) program. num = 0 while True: #deliberate infinite loop. True is always true. if num%1000 == 0: print(num) num += 1 ---------------------------------------------- You can categorize loops into "count-controlled loops" and "event-controlled loops". Most loops fall into one of these categories. Notions of a sentinel, a priming read, EOF, and flag ... Some typical uses of loops: counting, summing, and keeping track of a previous value. Whatever the category of loop, it's what the loop does that is the important thing. Note that all this categorization is for pedagogical purposes. The thing is not to learn how to distinguish between a sentinel-controlled summing loop from an EOF-controlled summing loop, but to write a loop that accomplishes what's needed. There won't be any exam questions that require you to know any of this terminology. You only need to be able to read and write loops. By read, I mean trace (e.g. show the output). I'm not sure if all the terminology and categorization helps or hinders learning. Don't get bogged down in it. Study the examples and do the exercises and programs. Nested Logic is very important. It's the natural extension of the earlier material. A loop can have a loop inside it. An example is code to count the number of commas on each line of input. The outer loop is looping over the lines, the inner loop is looping over the characters of a line. Display user-specified numbers of asterisks on multiple lines of output. The outer loop is looping over the user's input (numbers), the inner loops is looping the current user-number of times outputting an asterisk each iteration. It's getting hard to say in one sentence what these code fragments do. #input numbers from user. Display that number of *'s. #Negative number indicates end. num = eval(input("Enter a number: ")) #first number from user while num >= 0: #until a negative number is entered stars = 0 while stars < num: print("*") stars += 1 num = eval(input("Enter a number: ")) Code must be above all else correct; then you can worry about how efficient it is. In particular, you must be careful that a loop iterates the exact number of times needed, not one less or one more ("off by 1" errors). You can put prints in the loop to show the value of certain variables at certain points to help you see what's going on when things are not working right. These loops would be better with a 'for' statement: #input 5 numbers from user and sum them sum = 0 #initialize the sum to 0 count = 0 #count of number of numbers read while count < 5: #loop five times num = eval(input("Enter a number: ")) sum += num #add num to sum; short for sum = sum + num count += 1 #increment counter of numbers print("Sum is", sum) If the condition were: count <= 5 it would be an error, six numbers would be input and summed. But it would not be an error if additionally count was initialized to 1. If count were initialized to 1 instead of 0, and the condition stays as count<5, it would be an error, only four numbers would be input. These are known as "off by one" errors. You have to make sure that the code all works together correctly. ---------------------------------- It's rare that a program processes a constant number of values, like 5. Usually, the amount of data is variable. #user tells how many numbers to input and sum num_nums = eval(input("Enter number of numbers: ")) sum = 0 count = 0 while count < num_nums: #loop num_nums times num = eval(input("Enter a number: ")) sum += num count += 1 print("Sum is", sum)