0

I've been following CS Dojo's python series and learning on my own. At the end of the for loop tutorial, he asks us to find the sum of every multiple of 3 & 5 in range(1, 100). I did it on my own, but it was different from everyone else's in the comments. Did it again and got the same answer as everyone.

First attempt:

total4 = 0
for elements in range(1, 100):
    if elements % 3 or 5 == 0:
        total4 += elements
print(total4)
3267

Second attempt:

total4 = 0
for elements in range(1, 100):
    if elements % 3 == 0 or elements % 5 == 0:
        total4 += elements
print(total4)
2318

I know exactly what the second attempt is doing. But my question is why is the result for the first attempt so much higher than the second? What is being counted there? Apologies if its a silly question, I'm a beginner still, and want to fully understand what I'm doing before I move onto further tutorials.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 2
    Your first attempt captures a number if "elements % 3" is True, or "5 == 0" is True. The latter is never true, but the first will do exactly the opposite of what you want: All the numbers that are NOT multiples of 3. There are twice as many of those, so the number is higher. – Tim Roberts Oct 31 '22 at 22:41

1 Answers1

0

In your first for loop, one of your conditions is "elements % 3". Since you did not set not actually check if this is == 0, it assumes that you are checking elements % 3 == True. This will be true whenever elements % 3 is nonzero (0 is False and everything else is True). Also, the second part of your conditional statement checks that 5 == 0, not that element % 5 == 0.