python中while xxx 和 while xxx is not None的区别

python中while xxx 和 while xxx is not None的区别

while xxx(以一个列表为例)

​ 当xxx为None、False、空字符串、0、空列表、空字典、空元组时,xxx为False,反之xxx为True

lst1 = []
lst2 = [1,2,3]
while lst1:
    print(lst1)

while lst2:
    print(lst2.pop(), end=' ')

输出结果为:

3 2 1

lst1并没有输出

while xxx is not None

lst1 = []
lst2 = [1,2,3]
while lst1 is not None:
    print(lst1)
    break

while lst2 is not None:
    print(lst2.pop(), end=' ')

输出结果为:

[]
3 2 1 Traceback (most recent call last):
  File "D:/Anaconda3/envs/test.py", line 14, in <module>
    print(lst2.pop(), end=' ')
IndexError: pop from empty list

输出lst1时我用了break来结束循环,否则会一直输出,输出lst2时,程序报错。

你可能感兴趣的:(python中while xxx 和 while xxx is not None的区别)