Skip to main content

Command Palette

Search for a command to run...

bool() function in Python

Published
1 min read
bool() function in Python
A

Hello! I am Ashutosh and I enjoy creating things that live on the internet. I was first introduced to programming in my freshman year and since then, I started developing Web projects.

I am currently working at Thoughtworks India as an Application Developer.

Introduction

The bool() function converts a value to Boolean (True or False). If no value is passed to it, it returns False.

The syntax of bool() function is:

bool([value])

where value can be integers, sequence, mapping, etc.

Return Values

bool() function returns True if value is true, whereas False if value is false or no value is passed.

The following values are considered False in Python:

  • None
  • False
  • Zero of any numeric type. For example, 0, 0.0, 0j
  • Empty sequence. For example, (), [], ''.
  • Empty mapping. For example, {}
  • objects of Classes that has __bool__() or __len()__ method which returns 0 or False

All other values except these values are considered True.

Example

value = [] # Empty List
print(bool(value))

value = [0] # List with one element
print(bool(value))

value = 0.0 # Floating point number 0
print(bool(value))

value = None # None
print(bool(value))

value = True # Boolean True
print(bool(value))

value = 'non-empty string' # Non-Empty String
print(bool(value))

value = ''
print(bool(value)) # Empty String

Output:

False
True
False
False
True
True
False

Conclusion

In this part, we learned about the Python bool() function with the help of examples.

More from this blog

Ashutosh Writes

104 posts

Ashutosh enjoys creating things that live on the internet. He is passionate about full-stack development and DevOps. In his free time, he enjoys sharing his technical knowledge through articles.