Exercise: While loops
Practice while loops in these exercises, and run the doctests when you think you've got your code working. Remember, it's very easy (and common, even for experienced engineers) to code off-by-one errors, so keep your eyes peeled for those. 👀 Also, if you accidentally write an infinite loop, you will very likely crash the browser tab. If that happens, congratulations, that's a programmer rite of passage! Just reload the page and try to write a finite loop instead.
Count Evens
Implement count_evens
, a function that counts the number of even numbers between a given start
number and a given end
number. The count should include the start
or end
numbers if they are also even.
Tip: To check if a number is even, use the %
operator, which reports the remainder after dividing one number by another number. An even number divided by 2 has a remainder of 0.
📺 You can watch me walk through this problem in a video. If you don't want to see the solution, make sure to pause when you feel like you've seen enough to get started.
🧩 Or, for more guidance in written form, try a Parsons Puzzle version first.
Count Multiples
Implement count_multiples
, a function that counts how many multiples of a given divisor
are between the start
and end
numbers. It should include the start
or end
if they are also a multiple of divisor
.
Tip: The %
operator is once again helpful here, for determining if one number is a multiple of another. In fact, you may want to start from your previous code and see how little you need to change to get this function implemented correctly.
🧩 For more, try a Parsons Puzzle version first.
Sum Multiples
Implement sum_multiples
, a function that returns the sum of the multiples of a given divisor
between the given start
and end
numbers. If the start
or end
numbers are also multiples, they should also be included in the sum.
Hint: The main difference between this exercise and the previous exercise is summing versus counting. What do you need to change from your previous code to make the return value a sum instead?
Debug this! 🐞🐛🐜
The code for the next function is already written, but it has several bugs.
Tips for debugging:
- Read through the code and trace it on paper for small inputs
- Try running the tests and observe the output
- If you have a hunch, try changing the code and seeing how the output changes