5.33. Group Work: Functions with Loops

It is best to use a POGIL approach with the following. In POGIL students work in groups on activities and each member has an assigned role. For more information see https://cspogil.org/Home.

The Submit Group button will submit the answer for each each question on this page for each member of your group. It also logs you as the official group submitter.

Learning Objectives

Students will know and be able to do the following.

Content Objectives:

Process Objectives:

5.33.1. The For-Each Loop

A for-each loop in Python will loop though the items in a list starting with the item at index 0, then index 1, and so on till the last item in the list.

Run this code to see what it prints.

Drag the blocks from the left and put them in the correct order on the right to define a function total_even that returns the total of the even numbers in the passed list.

Fix the sum67 function below that takes a list and should return the total of the items in the list except for all the numbers between a 6 and 7 (inclusive). For example, sum67([1,2]) should return 3, but sum67([2, 6, 8, 7, 2]) should return 4.

5.33.2. Range and For

How do you loop just a set number of times? You can use the built-in range function to do this.

Run this code to see what it prints.

Note

The range(end) function will produce values from 0 to end - 1.

Run this code to see what it prints.

Note

The function range(start, end) will return a range object (an iterator) that allows you to loop from start (inclusive) to end (exclusive).

Run this code to see what it prints.

Drag the blocks from the left and put them in the correct order on the right to define a function total_at_odd_indices that returns the total of the numbers at odd indices in the passed list.

5.33.3. While Loops

A while loop repeats while a Boolean expression is True.

Try running the code below.

What do you think would happen if you deleted lines 6 and 7 in the above code?

Note

A loop that never ends is called an infinite loop. A while loop should have some way to end. If you have an infinite loop you may need to refresh the page to stop it.

Run this code to see what it prints.

Modify the code above to keep a count of the number of guesses and print the number of guesses it took to guess the correct value.

Fix the code below to print from start (inclusive) to 0 and then “Blastoff”

You have attempted of activities on this page