-2

I am getting a different answers from these two pieces of code. I am confused about this. Why is i % 3 == 0 or i % 5 == 0 different from i % 3 or i % 5 == 0?

>>>total = 0
>>>for i in range(1, 100):
>>>    if i % 3 == 0 or i % 5 == 0:
>>>        total += i
...print(total)
>>>total = 0
>>>for i in range(1, 100):
>>>    if i % 3 or i % 5 == 0:
>>>        total += i
...print(total)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • `i % 3` can be 0 or non 0. If it's a non-zero value, then it's true. So your expression will be equivalent to: `1 or i % 5 == 0` -> `True or whatever` -> `True`. – Maroun Oct 02 '20 at 10:51
  • Python is not a natural language... – iBug Oct 02 '20 at 10:55
  • Does this answer your question? [How do "and" and "or" act with non-boolean values?](https://stackoverflow.com/questions/47007680/how-do-and-and-or-act-with-non-boolean-values) – iBug Oct 02 '20 at 10:57
  • Thank u I got it from my friend. – Saneer Wadhwa Oct 02 '20 at 14:20
  • When we use -> if i % 3 or i % 5 == 0: it means i % 3 is not equal to 0 or i % 5 is equal to zero. – Saneer Wadhwa Oct 02 '20 at 14:24

1 Answers1

1

Just think about it like this (using parentheses):

>>>total = 0
>>>for i in range(1, 100):
>>>    if (i % 3 == 0) or (i % 5 == 0):
>>>        total += i
...print(total)

You are checking first if i%3 == 0 and then if i%5 == 0. In the second example you are checking if i % 3 is true or i % 5 == 0. Hopefully, you see that there is a big difference

basilisk
  • 1,156
  • 1
  • 14
  • 34