Link Search Menu Expand Document

Loop the loop

In this exercise we explore loops, an important concept in any programming language.

In a file named loop_theloop.py, write a function named loop that:

  • Takes three integer arguments: start, end, step
  • Returns the sum of all values generated by starting at start, adding step at each iteration and stopping once the value is greater than or equal to end
  • Uses 1 for the step value if the function is called with two arguments only

Calling loop(2,13,4) returns 18, for example, and calling loop(2,5) returns 9.

Mentoring topics

Discuss what happens when you call loop(2,13,-4), and how you could avoid problems in such a case.

Test code

To validate your code, download the test code below and run it as explained on the Hello, Python exercise page.

Test code: loop_theloop.py