Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python bool() Function

Python bool() Function

Python3 Built-in Functions Python3 built-in function


bool() is a built-in Python function that converts a value to a boolean.

A boolean has only two possible values:True(true) or False(false).

Word meaning: bool is short for boolean, denoting a logical value type.


Basic syntax and parameters

Syntax format


bool(x)

Parameter Description

- Type: any value - Description: the value to convert to a boolean.

Function description


Example

Example 1: basic usage

Example

Convert from various types

print

(

bool

(

1

)

)

         

Output: True

print

(

bool

(

0

)

)

         

Output: False

print

(

bool

(

1

)

)

       

Output: True

print

(

bool

(

""

)

)

       

Output: False

print

(

bool

(

"hello"

)

)

   

Output: True

print

(

bool

(

[

]

)

)

       

Output: False

print

(

bool

(

[

1

,

2

]

)

)

   

Output: True

print

(

bool

(

None

)

)

     

Output: False

print

(

bool

(

True

)

)

     

Output: True

print

(

bool

(

False

)

)

     

Output: False

Expected output:

True
False
True
False
True
False
True
False
True
False

Code analysis:

  1. The number 0 is False; nonzero numbers are True.
  2. An empty string is False; a non-empty one is True.
  3. An empty list is False; a non-empty list is True.

Example 2: common applications

Example

Check whether a list is empty

items

=

[

]

if

bool

(

items

)

:

   

print

(

"The list is not empty"

)

else

:

   

print

(

"The list is empty"

)

 

Output: The list is empty

Check whether a string has content

name

=

""

if

bool

(

name.

strip

(

)

)

:

   

print

(

f

"Hello, {name}"

)

else

:

   

print

(

"Please enter a name"

)

 

Output: Please enter a name

Check whether a value exists

data

=

{

"name"

:

"Tom"

}

if

bool

(

data.

get

(

"email"

)

)

:

   

print

(

"Has an email"

)

else

:

   

print

(

"No email"

)

 

Output: No email

Expected output:

列表为空
请输入名字
无邮箱

bool() Commonly used in conditionals to check whether a value exists or has content.


Python3 Built-in Functions Python3 built-in function