Presentation is loading. Please wait.

Presentation is loading. Please wait.

While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.

Similar presentations


Presentation on theme: "While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are."— Presentation transcript:

1 While loops

2 Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are called definite loops because we know how many times the loop needs to be executed There are situations where loops are needed but there is no way to determine ahead of time how many times they will run, this is an indefinite loop This is where a while loop becomes useful Anything that you can do with a for loop, you can do with an equivalent while loop There are things that can be done with a while which cannot be done with a for loop (at least, without using break!)

3 For loops To control a for loop you can use range function- range(10) iterates the variable from 0 to 9 a list- for i in [3, 9, 23, ‘a’, True]: (i gets every value in the list in that order) a string- for i in name: (i gets each character in the string in that order) (future) a file- for myline in infile: (myline gets each line in the file in turn)

4 While loop syntax while Boolean condition: body statements The Boolean condition is just like the ones in the if statements The body has to have at least one line, it can be as long as you like

5 While loop semantics When executing, the Boolean condition at the top is done first If it’s False, the body is skipped and execution continues with the next statement after the body (so the body may not be executed at all!) This is why a while loop is called a “pre-test” loop If the test is True, the body is executed the whole way through, then the Boolean condition at the top is evaluated again As long as the test stays True, the body will be executed It is possible to have an infinite loop, if the condition never changes – this is a bug!

6 While statement semantics

7 Controlling while loops You can control a while loop with a counter It is a little more code than for the equivalent for loop The other way to control a while loop is more general Any condition can be used as the Boolean expression at the top You can use user input (see Sentinel Logic) You can use calculations (“until the number reaches a given value”) You can use a flag that indicates some condition that occurred inside the loop

8 Sentinel Logic Assumes while loops and input statements

9 Sentinel Logic – uses an indefinite loop The for loop is a definite loop – you know how many times it needs to execute There are many situations in life / programming where you do not know this information (how many times it needs to execute) The while loop (indefinite loop) is made for this kind of situation. Example: “The loop executes until a sensor gives a value out of range” Example: “The user plays a game until they get tired.” Example: “The user inputs a value which must be either Y or N, nothing else.”

10 A pattern A pattern of statements called “sentinel logic” handles this kind of problem as cleanly as it can be done. A sentinel is an indicator that the loop can stop executing, that the data is used up. It can be a special number (-1, 0, 9999), a string (“stop”), or it can be a condition (keep looping while sensor > 0 and sensor < 50) Pattern Input the first data value to be processed While the data value is not the sentinel Process the data value Input the next data value to be processed

11 Nested Loops

12 Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures can be nested inside each other to any degree you need

13 Nested loops The general principle of nesting loops is that the inner loop must completely finish its execution before the next iteration of the outer loop starts Every time the outer loop iterates, the inner loop needs to start the control variable back at the beginning again

14 Nested for loops for i in range(10): for j in range(5): print(i, j) The nesting is shown by the indentation Different variables are used for the two loops, i and j, for clarity Other statements can be inside the outer loop, not just the inner loop

15 Nested while loops These work on the same principles as the for loops If they are controlled by counters, make sure the initializations of the counters are where they need to be. That is, if the inner loop needs to have its counter set to zero before the loop, you must decide whether the initialization needs to be inside the outer loop or outside the outer loop ct1 = 0 while ct1 < 5: ct2 = 0 while ct2 < 10: print(ct1, ct2) ct2 += 1 ct1 += 1

16 Data Validation while loops

17 Data validation Programs get input data from different sources All data should be ‘validated’ before the program tries to process it Depends on the specifications – what is valid data in your problem? May be general “numbers greater than zero” May be specific “only Y or N allowed”

18 What to do when invalid? What does your code do when invalid data is seen? Depends on the specification again Possible actions for invalid data stop the program (with explanatory error message, please!) give the user another chance to enter data (from the keyboard, probably) use a default value for the data and proceed as usual skip the bad data and proceed as usual (not always possible)

19 Using sentinel logic to validate keyboard input The requirement is that the user must enter Y or N or Q, nothing else Design ask the user for input while the input is NOT valid display an error message (with acceptable inputs shown) ask the user for input The trickiest part is the condition for the while while inp != ‘Y’ and inp != ‘N’ and inp != ‘Q’: is what you need. A common mistake is to use or instead of and If both cases of letters are allowed, it is simpler to change the input to one case, then test as above (remember the.upper and.lower methods)


Download ppt "While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are."

Similar presentations


Ads by Google