Skip to main content
 首页 » 编程设计

python之`If` 行的语法错误

2025年05月04日11jillzhang

我的代码:

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