python - `If` 行的语法错误

标签 python syntax

我的代码:

#!/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

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

最佳答案

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 - `If` 行的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1574530/

相关文章:

python - 使用 selenium 将音频从文件传递到 Chrome

python - 从 errbot 将数据返回到 Slack

java - 为什么没有编译时错误?奇怪 - Java

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : Unknown column 'Smith' in 'where clause'

c++ - Python ImportError - undefined symbol - 用于自定义 C++ 模块

Python戴尔驱动程序下载

python - 将 `numpy.linalg.det` 作为方法添加到 `numpy.matrix`

java - 符号 "Class<?>... "

haskell - 这个 Haskell 代码的语法规则是什么?

c - 将数组传递给函数时出现语法错误