Python:期望缩进块

ric*_*low 1 python if-statement indentation

我认为一切都在这里正确缩进但我得到一个IndentationError:期望else:语句中有一个缩进块.我在这里犯了一个明显的错误吗?

def anti_vowel(text):
    new_string = ""
    vowels = "aeiou"
    for letter in text:
       for vowel in vowels:
           if (lower(letter) == vowel):
               #do nothing
           else:
               #append letter to the new string
               new_string += letter
    return new_string
Run Code Online (Sandbox Code Playgroud)

Bre*_*arn 7

你需要在if块内放一些东西.如果你不想做任何事,请把pass.

或者,只需改变您的条件,这样您只有一个块:

if lower(letter) != vowel:
    new_string += letter
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我认为你的代码不会按照你的意图去做,但这是另一个问题的问题.


Cil*_*yan 5

不执行任何操作转换为使用pass关键字填充否则为空的块(不允许).有关更多信息,请参阅官方文档.

def anti_vowel(text):
    new_string = ""
    vowels = "aeiou"
    for letter in text:
       for vowel in vowels:
           if (lower(letter) == vowel):
               #do nothing
               pass
           else:
               #append letter to the new string
               new_string += letter
    return new_string
Run Code Online (Sandbox Code Playgroud)

  • 很好的教程链接进一步解释. (2认同)