-3

I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:

def prob11(abc):
    if 7 and 0 and 0 not in abc:
        return False
    x = abc.index(0)
    elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
        return True
    else:
        return False

I get this error:

File "<ipython-input-12-e2879221a9bf>", line 5
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
   ^
SyntaxError: invalid syntax

Whats wrong with my elif statement?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
MNIShaurya
  • 111
  • 6
  • 3
    I suggest you look a https://docs.python.org/3/tutorial/controlflow.html#if-statements, you cannot have `x = abc.index(0)` within the if else like that. All statements within `if-elif-else` are at the next indentation level – Devesh Kumar Singh Apr 11 '20 at 17:05
  • Also, `7 and 0 and 0 not in abc` does not mean what you expect it to mean. – Karl Knechtel Apr 11 '20 at 17:08
  • 1
    `if 7 and 0 and 0 not in abc:` is always `False` - please read the dupe and recheck the documentation about if/elif/else. – Patrick Artner Apr 11 '20 at 17:08
  • @PatrickArtner while the code seems to have the issue in question (https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) that you've linked as a duplicate (although I'm not entirely clear on how OP intends for the logic to work), it doesn't address the syntax question being asked. I'm voting to reopen. – Karl Knechtel Apr 11 '20 at 17:09
  • Next problem you are going to run into: [how-to-test-multiple-variables-against-a-value](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Patrick Artner Apr 11 '20 at 17:11
  • @Karl then dupe it for https://stackoverflow.com/questions/7025443/else-elif-statements-not-working-in-python – Patrick Artner Apr 11 '20 at 17:11
  • Either your logic or your indentation is incorrect. You terminated the `if` with the `x=` statement at the same indentation level. Therefore, your `elif` and `else` have no `if` to match them; they're illegal. – Prune Apr 11 '20 at 17:24

2 Answers2

0

You could try this one, hope it's helpful.

def prob11(abc):
    if 7 in abc and abc.count(0) >= 2:
        return True
    else:
        return False

print(prob11([0, 0, 7]))
# print True

print(prob11([0, 0, 6]))
#print False
SHiSA
  • 45
  • 5
Seven Cash
  • 53
  • 8
0

I am not sure if this would be the best/fastes way to do your problem but this worked for me:

def checker(abc):
    if 7 or 0 in abc:
        print('yes1')
        if all(x in abc for x in [0, 0, 7]):
            print('yes2')
            if sorted(abc)==abc:
                print('yes3')

abc=[0,0,7]
v=checker(abc)

Your code wouldn't work, because the in and and won't work that way. I am not sure why. So instead you need to use the all function.

SHiSA
  • 45
  • 5