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

“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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值