5.8-5.10 computer science
Break
A break statement in a loop causes an immediate exit of the loop. A break statement can sometimes yield a loop that is easier to understand. for num_empanadas in range(max_empanadas + 1): meal_cost = (num_empanadas * empanada_cost) + (num_tacos * taco_cost) # Find first meal option that exactly matches user money if meal_cost == user_money: break = Enter money for meal: 20 $20 buys 4 empanadas and 2 tacos without change. The nested for loops generate all possible meal options for the number of empanadas and tacos that can be purchased. The inner loop body calculates the cost of the current meal option. If equal to the user's money, the search is over, so the break statement immediately exits the inner loop. The outer loop body also checks if equal, and if so that break statement exits the outer loop 5.10
Developing programs incrementally
Experienced programmers develop programs incrementally, starting with a simple version of the program, and then growing the program little-by-little into a complete version. Do a very basic form of the program- and then build on it 5.9
FIXME Comment
FIXME comment attracts attention to code that needs to be fixed. Many editors automatically highlight FIXME comments. Large projects with multiple programmers might also include a username and date, as in FIXME(01/22/1997, John). 5.9
Continue
continue statement in a loop causes an immediate jump to the while or for loop header statement. A continue statement can improve the readability of a loop. The example below extends the previous meal finder program to find meal options for which the total number of items purchased is evenly divisible by the number of diners. In addition, the following program will output all possible meal options, instead of reporting the first meal option found. Ex- for num_tacos in range(max_tacos + 1): for num_empanadas in range(max_empanadas + 1): # Total items purchased must be equally divisible by number of diners if (num_tacos + num_empanadas) % num_diners != 0: continue meal_cost = (num_empanadas * empanada_cost) + (num_tacos * taco_cost) = Enter money for meal: 60 How many people are eating: 3 $60 buys 12 empanadas and 6 tacos without change. $60 buys 0 empanadas and 15 tacos without change. 2 nested loops in this ex. 5.10
Nested loop
loop that appears as part of the body of another loop is called a nested loop, these loops are commonly referred to as the outer loop and inner loop. Nested loops have various uses. One use is to generate all combinations of some items 5.8