How to make exceptions during the iteration of a for loop in python
<p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p>

<p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p>

<pre><code>odds = '1 3 5 7 9'.split()
for i in range(x):
   if i in odds: 
      continue
   print(i)
</code></pre>

<p>this code works for <code>if i == y</code> but I cannot get it to work with a specific set of "y"s</p>

<p>This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an <code>int</code> in a list of <code>str</code> objects.</p>

<p>So the <code>if</code> test never matches, because there is no <code>1</code> in the list <code>['1', '3', '5', '7', '9']</code>; there is no <code>3</code> or <code>5</code> or <code>7</code> or <code>9</code> either, because an integer is a different type of object from a string, even if that string contains digits that look, to you as a human, like digits.</p>

<p>Either convert your int to a string first, or convert your strings to integers:</p>

<pre><code>if str(i) in odds:
</code></pre>

<p>or</p>

<pre><code>odds = [int(i) for i in '1 3 5 7 9'.split()]
</code></pre>

<p>If you want to test for odd numbers, there is a much better test; check if the remainder of division by 2 is 1:</p>

<pre><code>if i % 2 == 1:  # i is an odd number
</code></pre>

python python-3.x if-statement for-loop nested