【问题标题】:syntax error on `If` line`If​​` 行上的语法错误
【发布时间】:2010-12-07 04:01:51
【问题描述】:

我的代码:

#!/usr/bin/env python

def Runaaall(aaa):
  Objects9(1.0, 2.0)

def Objects9(aaa1, aaa2):
  If aaa2 != 0: print aaa1 / aaa2

我收到的错误:

$ python test2.py 
  File "test2.py", line 7
    If aaa2 != 0: print aaa1 / aaa2
          ^
SyntaxError: invalid syntax

我不知道为什么会发生这个错误。

【问题讨论】:

  • 你用什么python教程来学习语言?
  • @S.Lott: :) 我猜他没有听从你的建议stackoverflow.com/questions/1573548/…
  • @SilentGhost:好点。我很少查看是谁提出的问题。这似乎是两个具有相同不良行为的问题:输入随机内容并希望它有效。

标签: python syntax


【解决方案1】:

if必须小写。

此外,

  • 以小写形式编写函数名称(参见PEP 8,Python 风格指南)。
  • if 子句的正文写在单独的行上。
  • 虽然在这种情况下您可能不会遇到麻烦,但请小心comparing floats for equality
  • 由于您刚刚开始学习 Python,您可能想熟悉在 print 的参数周围写括号,因为从 Python 3 开始,print is a function,而不是关键字。
    要在 Python 2.6 中强制执行此语法,您可以将其放在文件的顶部:

    from __future__ import print_function
    

    演示:

    >>> print 'test'
    test
    >>> from __future__ import print_function
    >>> print 'test'
      File "<stdin>", line 1
        print 'test'
                   ^
    SyntaxError: invalid syntax
    >>> print('test')
    test
    

    有关__future__ 导入的更多信息,请参阅documentation

【讨论】:

  • 最后一点可以通过在python 2.6上使用from future import print_function来实现
  • 好点,巴托兹。我用更多信息更新了答案。
【解决方案2】:

怎么样

def Objects9(aaa1, aaa2):
  if aaa2 != 0: print aaa1 / aaa2

Python 关键字区分大小写,因此您必须使用 'if' 而不是 'If'、'for' 而不是 'fOR' 等等。

【讨论】:

    【解决方案3】:

    它是“If”中的大写“I”。把它改成“if”就可以了。

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2016-05-23
      • 2015-09-08
      • 2011-09-22
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多