0

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

3
  • 1
    odds is a list of strings. i is an integer.. Commented Oct 8, 2016 at 7:50
  • I can't tell if you want to print even or odd numbers from your question. You are using range, which suggests you are looking to iterate over a range of values rather than the values of a list. You may need to clarify this. Commented Oct 8, 2016 at 8:00
  • I was looking for a way to exclude i's in a for loop. I just gave this example because it was simple the actual program i'm writing is more complex. In this example I would have liked for every variable to be iterated over but only for the evens to have been printed since the the odds would hit the 'continue' statement. Commented Oct 9, 2016 at 17:38

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.