Question: The template for a for-loop is for in : where each element in is used once each time the loop body is executed. On each

The template for a for-loop is

 for  in :  

where each element in is used once each time the loop body is executed. On each pass of the loop this element is assigned to . In Python there are a variety of iterables, including lists, tuples, and strings. When the first pass of the loop is initiated, a lists first element is assigned to . When the second pass is initiated, its second element is assigned to and so on until all the elements have been used and the looping ends. serves as the loop variable. Any valid identifier can be used for . In some loops were interested in using in the body of the loop while in other loops this value is ignored (in such loops is typically used as a counter for which there may not be a need).

For this task, youll use for-loops in two different ways. Youll use a counter and the items in thelist itself, and youll use an accumulator. Note, however, that its important to remember thatfor-loops can be used with any iterable, not just lists! Well again be using the IDLE Shell window interactive environment.

First create an empty list called numbers. Then initialize a counter i by assigning it to a value of 1. Next write a for-loop that uses fave as the loop variable and your top ten list as the iterable. The output of your code should look similar to the following (but with your favorite items, not mine). For each pass of the loop, append the counter to the numbers list and then use augmented assignment as discussed in class to increment the value of the counter.

1. almond croissants 2.art 3. cookies 4. cruises

5. dark chocolate 

1 2 3 4 5

2

  1. 6 6. espresso

  2. 7 7. long, sunny summer days

  3. 8 8. reading

  4. 9 9. sleeping

  5. 10 10. working out

    Next, use a for-loop to sum the numbers in your numbers list and then find the average using the len() function in the denominator. Use augmented assignment to add to your accumulator. Dont forget to initialize your accumulator to 0! Your answer should be 5.5.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!