Source code available on GitHub.
This first problem gets us off to an easy start. It asks:
We want to iterate through all the numbers below 1000, so we’ll use a for
loop:
for i in range(1,1000):
This tells Python to start with i=1
and keep incrementing i
every loop up until i=999
. The easiest way to check for divisibility is with the modulus operator, %
. Writing x % y
returns the value of – that is, the remainder when dividing
by
.
So, using an if
statement, we write
if i % 3 == 0 or i % 5 == 0:
which will return true when the number is a multiple of (had zero remainder when divided by) either 3 or 5. If this happens, we want to add i
to some sum so that when the for
loop terminates, that value is our final value. We’ll call it running_sum
.
Lastly, we want to print the result. Here’s the final code:
running_sum = 0 for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: running_sum += i print(running_sum)