Python中elif语句的语法错误 [英] Syntax Error on elif statement in Python

查看:1901
本文介绍了Python中elif语句的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Python 2.7编写的代码时遇到了一些麻烦。它给我一个关于elif语句的语法错误,但是没有解释,我在代码中找不到任何合理的错误。 (字体是我定义的方法。)

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."]

错误:

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


推荐答案

elif 之前,您有一个未缩进的三引号字符串文字:

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

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

......字符串文字多行注释。他们创建字符串,只是因为你忽略了生成的字符串对象,Python忽略了这一行。它们仍然是Python语法的一部分;你使用它们时不能忽略缩进规则。

"""...""" 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.

使用正确的注释:

# 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.

如果您必须使用三重引用字符串作为块注释,则必须将它们缩进为如果 elif 阻止他们被放入:

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:
    # ...

这篇关于Python中elif语句的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆