Syntax Error on elif statement in Python

邮差的信 提交于 2019-12-11 11:43:46

问题


I was having a bit of trouble with this code that I wrote in Python 2.7. It's giving me a syntax error on the elif statement, but there's no explanation and I can't find any reasonable error in the code. (typeline is a method I defined.)

num = randrange(-25,15)
""" Toxic """
if num >= -25 and num < -10:
        responses = ["Ugh, nasty.", "That was absolutely disgusting.", "My stomach feels like it's going to explode.", "Pardon me if I puke."]
        typeline(responses[randrange(0,4)], "jack")
        return [num, "Jack ate a VERY TOXIC FRUIT and survived.", "Jack ate a VERY TOXIC FRUIT and died."]
""" Mildly poisonous """
elif num >= -10 and num < 0: """ SYNTAX ERROR HERE """
        responses = ["Yuck", "It's kinda bitter.", "Tastes like an unripe banana.", "It's not so bad."]
        typeline(responses[randrange(0,4)], "jack")
        return [num, "Jack ate a MILDLY TOXIC FRUIT and survived.", "Jack ate a MILDLY TOXIC FRUIT and died."]
""" Healthy """
else:
        responses = ["Definitely not too bad", "It's almost kind of tasty!", "Should I make a jam out of this?", "This is my new favorite fruit."]
        typeline(responses[randrange(0,4)], "jack")
        return [num, "Jack ate a HEALTHY FRUIT and was rescued.", "Jack ate HEALTHY FRUIT and survived."]

The error:

  File "<stdin>", line 9
    elif num >= -10 and num < 0:
       ^
SyntaxError: invalid syntax

回答1:


You have an unindented triple-quoted string literal right before the elif:

""" Mildly poisonous """
elif num >= -10 and num < 0:

"""...""" string literals are not multi-line comments. They create strings, and only because you then ignore the string object produced does Python ignore the line. They are still part of the Python syntax; you can't ignore indentation rules when you use them.

Use proper # comments instead:

# Toxic
if num >= -25 and num < -10:
    # ...
# Mildly poisonous
elif num >= -10 and num < 0:
    # ...
# Healthy
else:
    # ...

Since comments are ignored altogether by the syntax, it doesn't matter how they are indented.

If you must use """ ... """ triple-quoted strings as 'block comments', you must indent them to be part of the if or elif block they are placed in:

""" Toxic """
if num >= -25 and num < -10:
    # ...
    """ Mildly poisonous """
elif num >= -10 and num < 0:
    # ...
    """ Healthy """
else:
    # ...


来源:https://stackoverflow.com/questions/37124588/syntax-error-on-elif-statement-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!