Python Boolean

Summary: in this tutorial, you’ll learn about the Python boolean data type, falsy and truthy values.

Introduction to Python Boolean data type #

In programming, you often want to check if a condition is true or not and perform some actions based on the result.

To represent true and false, Python provides you with the boolean data type. The boolean value has a technical name as bool.

The boolean data type has two values: True and False.

Note that the boolean values True and False start with the capital letters (T) and (F).

The following example defines two boolean variables:

is_active = True
is_admin = FalseCode language: Python (python)

When you compare two numbers, Python returns the result as a boolean value. For example:

x = 20
y = 10

result = x > y
print(result)

result = x < y
print(result)Code language: Python (python)

Try it

Output:

True
FalseCode language: PHP (php)

Also, comparing two strings results in a boolean value:

x = 'a'
y = 'b'

result = x > y
print(result)

result = x < y
print(result)Code language: Python (python)

Try it

Output:

False
TrueCode language: PHP (php)

The bool() function #

To find out if a value is True or False, you use the bool() function. For example:

result = bool('Hi')
print(result)

result = bool(100)
print(result)

result = bool(0)
print(result)Code language: Python (python)

Try it

Output:

True
True
FalseCode language: PHP (php)

The output indicates some values evaluate to True and the others evaluate to False.

Falsy and Truthy values #

When a value evaluates to True, it’s truthy. If a value evaluates to False, it’s falsy.

The following are falsy values in Python:

  • The number zero (0)
  • An empty string ''
  • False
  • None
  • An empty list []
  • An empty tuple ()
  • An empty dictionary {}

The truthy values are the other values that aren’t falsy.

Note that you’ll learn more about the None, list, tuple, and dictionary in the upcoming tutorials.

Summary #

  • Python boolean data type has two values: True and False.
  • Use the bool() function to test if a value is True or False.
  • Falsy values evaluate to False whereas truthy values evaluate to True.
  • Flasy values are the number zero, an empty string, False, None, an empty list [], an empty tuple (), and an empty dictionary {}.
  • Truthy values are the values that are not Falsy.

Quiz #

Was this tutorial helpful ?