Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Machine Learning And Knowledge Discovery In Databases European Conference Ecml Pkdd 2016 Riva Del Garda Italy September 19 23 2016 Proceedings Part 1 Lnai 9851

Authors: Paolo Frasconi ,Niels Landwehr ,Giuseppe Manco ,Jilles Vreeken

1st Edition

3319461273, 978-3319461274

More Books

Students also viewed these Databases questions