Loops – How to do Repetitive Tasks Easy

A loop can iterate over the same task multiple times. It can be over a range, the items of a list, or something similar.

Let’s get started and try it out.

  • Step 1: Can you see what the code below does?
  • Lesson:
    • The for-loop executes the following indented lines for each iteration.
    • The for-loop over a list will assign each element to the looping variable (for item in my_list, assigns item each element of the my_list and executes the following indented lines)
  • Step 2: Append an integer to my_list, such that the sum becomes 20.
    • Hint: Use append on my_list between the 1st and 2nd line.
  • Step 3: See how range can help you repeat a task with a counter i.
  • Lesson: If you need to repeat a task multiple times you can use a for-loop with range (example, for i in range(100): will repeat the following indented code 100 times, where the variable i is increment from 0 to 99 for each iteration).
  • Step 4: Change the second for-loop, such that it calculates the sum.
    • Hint: You need to create an additional variable sum and assign it to zero before the for-loop.
  • Step 5: Sometimes you do need to iterate over a list or a range of times. What to do then? Inspect the code below before you execute it.
  • Lesson: A while-loop will continue as long as the boolean expression is true.
    • Example while True: will run forever.
  • Step 6: You can use continue and break in the loops as the example below shows.
  • Lesson: A for-loop or a while-loop can use continue and break.
    • continue: when reached it will start with the next iteration, ignoring the following lines of code.
    • break: will terminate the loop and continue to execute the line after the loop.
  • Exercise: Calculate the sum of the integers in my_list up until you reach the first integer greater than 100 (to not include it in your sum).
    • Hint 1: The result should be 387.
    • Hint 2: Use a variable sum to count.
    • Hint 3: Use break if an item is greater than 100.
    • Hint 4: See solution.py for a possible answer.

Leave a Reply

%d bloggers like this: