我的Python else语句被读作无效语法

时间:2014-02-19 23:09:10

标签: python if-statement syntax

(这是在进行中) 您好,我正在学习一门名为“Code Academy”的Python课程,我正在为PygLatin Translator制作英语。当我编译我的代码时,我收到一条错误消息

File "python", line 8
    else:
       ^
SyntaxError: invalid syntax

任何帮助都将受到高度赞赏:),这是我的代码。

pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
    word = original.lower()
first = word[0]
print original
else:
print 'empty'

2 个答案:

答案 0 :(得分:3)

你的缩进是错误的。这三行:

first = word[0]

print original

print 'empty'

需要缩进一个级别:

pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = word[0]
    print original
else:
    print 'empty'

请记住缩进在Python中很重要。

答案 1 :(得分:0)

我不确定这应该是答案还是评论,但是你的格式搞砸了,这可能就是你遇到问题的原因。

请记住,在Python中,空格很重要。看起来你在if区块的中途没有缩进,所以你的else正处于不知名的地方(对于翻译)。

pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
    word = original.lower() # entered if block
first = word[0] # exited if block
print original
else: # else?? else what, there's no if!!!
print 'empty' # and what's more there's nothing IN the else block, this line is unindented

我会在这里猜测你的意思,但翻译不会。我的猜测是你打算写:

pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
    # if this condition is true, then do...
    word = original.lower()
    first = word[0]
    print original
else:
    # if that condition up there ISN'T true, do...
    print 'empty'