【问题标题】:My Python else: statement is read as invalid syntax我的 Python else: 语句被读取为无效语法
【发布时间】:2014-02-19 23:09:09
【问题描述】:

(正在进行中) 您好,我正在学习一门名为“代码学院”的 Python 课程,并且正在制作英语到 PygLatin 的翻译器。当我编译我的代码时,我收到一条错误消息说

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'

【问题讨论】:

    标签: python if-statement syntax


    【解决方案1】:

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

    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 中很重要。

    【讨论】:

      【解决方案2】:

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

      请记住,空格在 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多