What is the correct way to use and logical operator in python for multiple conditions?
<p>I'm trying to brute-force a projecteuler questions before I improve my code. I can't get multiple condition and logical operator working in my loop. Here is the code, editor shows no errors but it simply don't increase condition value so obviously some of the conditions are wrong. Can some one show me the correct way to use multiple and logical operators?</p>

<pre><code>i = 20

while (i % 2 != 0 and i % 3 != 0 and i % 4 != 0 and i % 5 != 0 and
     i % 6 != 0 and i % 7 != 0 and i % 8 != 0 and i % 9 != 0 and
     i % 10 != 0 and i % 11 != 0 and i % 12 != 0 and i % 13 != 0 and
     i % 14 != 0 and i % 15 != 0 and i % 16 != 0 and i % 17 != 0 and
     i % 18 != 0 and i % 19 != 0 and i % 20 != 0):
    i = i + 20
else:
    print(i)
</code></pre>

<p>It looks like you're trying to find the smallest number which is a multiple of all integers from 1 to 20 inclusive.  You're starting with 20, and you want to keep going up by 20 until your condition is met.</p>

<p>It's easier to see the problem in a smaller case.  Say we only cared about 2, 3, and 4.</p>

<p>We want to find a number i for which </p>

<pre><code>i % 2 == 0 and i % 3 == 0 and i % 4 == 0
</code></pre>

<p>But the negation of this is either</p>

<pre><code>not (i % 2 == 0 and i % 3 == 0 and i % 4 == 0)
</code></pre>

<p>or, distributing the <code>not</code>,</p>

<pre><code>i % 2 != 0 or i % 3 != 0 or i % 4 != 0
</code></pre>

<p>In other words, if <em>any</em> of the numbers fail to divide evenly, you want to increase by 20, not if <em>all</em> of them fail to.  </p>

<p>20, for example, is divisible by 2, so <code>i % 2 != 0</code> is False, so you have <code>False and i % 3 != 0 and.. etc</code>, which will still be false.  A working version of your code would look like</p>

<pre><code>i = 20
while any(i % num != 0 for num in range(2,21)):
    i += 20
</code></pre>

<p>where I've used a generator expression to avoid all the duplication.  Note thought that this will be <em>very much</em> slower than using the math trick they want you to use, because the final answer has 9 digits..</p>

python operators brute-force logical