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时,程序报错。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Python,"in"是一个操作符,用于判断一个元素是否存在于一个序列、集合或映射具体来说,它用于成员判断,返回结果为True或False。对于序列(如字符串、元组、列表)或集合(如set)或映射(如字典)这些数据类型,"in"操作符可以用在诸如if xx in xxx、while xx in xxx等需要进行成员判断的情况。对于数组/列表,在Python,"in"操作符会检查值而不是索引,这和JavaScript的行为不同。对于对象,在JavaScript,如果对象具有名为'1'的成员或方法,则1 in d的结果为true;而在Python,这取决于类的定义。Python会尝试调用d.__contains__(1),如果失败,则会尝试将对象视为可迭代对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python的in是什么意思](https://blog.csdn.net/weixin_35973118/article/details/114934925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [在if语句“ in”的使用和含义?](https://blog.csdn.net/weixin_39624367/article/details/110897314)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [if语句“ in”的使用和含义?](https://blog.csdn.net/weixin_39962394/article/details/110897296)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值