“SyntaxError: Missing parentheses in call to ‘print’”
先看一个错误:
>>> a = 1
>>> print a
File "<stdin>", line 1
print a
^
SyntaxError: Missing parentheses in call to 'print'
>>> print(a)
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这样的关键字:
>>> Null
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Null' is not defined
>>> NULL
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'NULL' is not defined
>>> nullptr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'nullptr' is not defined
所以接下来要隆重介绍一下None
None和False不同:
>>> None == False
False
None不是0:
>>> None == 0
False
None不是空字符串:
>>> None == ''
False
None和任何其他的数据类型比较永远返回False:
>>> None == 1
False
>>> None == 1.2
False
None有自己的数据类型NoneType:
>>> type(None)
<class 'NoneType'>
Python’s None is Object-Orientated
None是使用is还是==
null_variable = None
not_null_variable = 'Hello There!'
# The is keyword
if null_variable is None:
print('null_variable is None')
else:
print('null_variable is not None')
if not_null_variable is None:
print('not_null_variable is None')
else:
print('not_null_variable is not None')
# The == operator
if null_variable == None:
print('null_variable is None')
else:
print('null_variable is not None')
if not_null_variable == None:
print('not_null_variable is None')
else:
print('not_null_variable is not None')
输出:
null_variable is None
not_null_variable is not None
null_variable is None
not_null_variable is not None
特俗情况,类中:
class MyClass:
def __eq__(self, my_object):
# We won't bother checking if my_object is actually equal
# to this class, we'll lie and return True. This may occur
# when there is a bug in the comparison class.
return True
my_class = MyClass()
if my_class is None:
print('my_class is None, using the is keyword')
else:
print('my_class is not None, using the is keyword')
if my_class == None:
print('my_class is None, using the == syntax')
else:
print('my_class is not None, using the == syntax')
输出:
my_class is not None, using the is keyword
my_class is None, using the == syntax