python中bool怎么用_bool()在Python中的实际应用是什么?

When it is being used in everyday coding? I am learning Python using this tutorial. What am I referring to is described here (middle of the page), but I can't get it. I understand the principles of using True and False, but I don't get when (or do) we actually use the bool() function in practice while writing our code. It would help me if you give the everyday, practical example of bool() in code.

解决方案

It lets you convert any Python value to a boolean value.

Sometimes you want to store either True or False depending on another Python object. Instead of:

if python_object:

result = True

else:

result = False

you simply do:

result = bool(python_object)

How Python objects are converted to a boolean value, all depends on their truth value. Generally speaking, None, numeric 0 and empty containers (empty list, dictionary, set, tuple, string, etc.) are all False, the rest is True.

You use it whenever you need an explicit boolean value. Say you are building an object tree, and you want to include a method that returns True if there are children in the tree:

class Tree(object):

def __init__(self, children):

self.children

def has_children(self):

return bool(self.children)

Now Tree().has_children() will return True when self.children is not empty, False otherwise.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值