Vendelisk
Vendelisk

Reputation: 23

How to make exceptions during the iteration of a for loop in python

Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an if ______ in ____: block into an existing for block.

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

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

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

Upvotes: 0

Views: 100

Answers (2)

OrderAndChaos
OrderAndChaos

Reputation: 3860

If you are looking to iterate over a range of even numbers, then something like this should work. With X being an integer. The 2 is the step so this will omit odd numbers.

for i in range(0,x,2):
    print(i)

For more info check out the docs here:

https://docs.python.org/2/library/functions.html#range

I ran in to a couple of problems with the code you provided, continue would just fall through to the print statement and the values in odds where chars not ints which meant the comparison failed.

Creating a list of integers and using not in instead of in will get around this.

x = 10
odds = [1, 3, 5, 9]
for i in range(x):
    if i not in odds:
        print(i)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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

So the if test never matches, because there is no 1 in the list ['1', '3', '5', '7', '9']; there is no 3 or 5 or 7 or 9 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.

Either convert your int to a string first, or convert your strings to integers:

if str(i) in odds:

or

odds = [int(i) for i in '1 3 5 7 9'.split()]

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

if i % 2 == 1:  # i is an odd number

Upvotes: 4

Related Questions