Python中的None和空(“SyntaxError: Missing parentheses in call to 'print'”)

浅浅的花香味﹌ 2022-07-14 01:48 389阅读 0赞

“SyntaxError: Missing parentheses in call to ‘print’”

先看一个错误:

  1. >>> a = 1
  2. >>> print a
  3. File "<stdin>", line 1
  4. print a
  5. ^
  6. SyntaxError: Missing parentheses in call to 'print'
  7. >>> print(a)
  8. 1

这是什么鬼?

这是Python2和Python3的区别,在Python3中,不能使用print a,需要加括号。

进入正题!

\ None和空**

Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton, testing for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.

首先需要明确,Python中没有Null NULL nullptr这样的关键字:

  1. >>> Null
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name 'Null' is not defined
  5. >>> NULL
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. NameError: name 'NULL' is not defined
  9. >>> nullptr
  10. Traceback (most recent call last):
  11. File "<stdin>", line 1, in <module>
  12. NameError: name 'nullptr' is not defined

所以接下来要隆重介绍一下None
None和False不同:

  1. >>> None == False
  2. False

None不是0:

  1. >>> None == 0
  2. False

None不是空字符串:

  1. >>> None == '' False

None和任何其他的数据类型比较永远返回False:

  1. >>> None == 1
  2. False
  3. >>> None == 1.2
  4. False

None有自己的数据类型NoneType:

  1. >>> type(None)
  2. <class 'NoneType'>

Python’s None is Object-Orientated

None是使用is还是==

  1. null_variable = None
  2. not_null_variable = 'Hello There!'
  3. # The is keyword
  4. if null_variable is None:
  5. print('null_variable is None')
  6. else:
  7. print('null_variable is not None')
  8. if not_null_variable is None:
  9. print('not_null_variable is None')
  10. else:
  11. print('not_null_variable is not None')
  12. # The == operator
  13. if null_variable == None:
  14. print('null_variable is None')
  15. else:
  16. print('null_variable is not None')
  17. if not_null_variable == None:
  18. print('not_null_variable is None')
  19. else:
  20. print('not_null_variable is not None')

输出:

  1. null_variable is None
  2. not_null_variable is not None
  3. null_variable is None
  4. not_null_variable is not None

特俗情况,类中:

  1. class MyClass:
  2. def __eq__(self, my_object):
  3. # We won't bother checking if my_object is actually equal
  4. # to this class, we'll lie and return True. This may occur
  5. # when there is a bug in the comparison class.
  6. return True
  7. my_class = MyClass()
  8. if my_class is None:
  9. print('my_class is None, using the is keyword')
  10. else:
  11. print('my_class is not None, using the is keyword')
  12. if my_class == None:
  13. print('my_class is None, using the == syntax')
  14. else:
  15. print('my_class is not None, using the == syntax')

输出:

  1. my_class is not None, using the is keyword
  2. my_class is None, using the == syntax

发表评论

表情:
评论列表 (有 0 条评论,389人围观)

还没有评论,来说两句吧...

相关阅读