Skip to content

How to print Boolean values in Python

Learn how to display, format, and convert Python boolean values (True/False) using print(), f-strings, type checks, and conversions to integers or strings.

Boolean values (True and False) are fundamental in programming for representing truth and state.

This guide will explore various methods to print, format, and convert boolean values in Python, ensuring you can effectively use them in your code and display them appropriately.

Printing Boolean Values Directly

The simplest way to display a boolean value is to pass it directly to the print() function:

my_bool = True
print(my_bool)  # Output: True
print(False)    # Output: False

The print() function outputs the boolean value to the console without any additional formatting.

Printing Boolean Values within Strings

To embed a boolean value within a string, use f-strings (formatted string literals). F-strings allow you to include expressions inside string literals:

my_bool = True
print(f'is subscribed: {my_bool}')  # Output: is subscribed: True

Checking Variable Types with type() and isinstance()

If you're unsure of the data type of a variable, use the built-in type() function or the isinstance() function:

my_bool = False
print(type(my_bool))                # Output: <class 'bool'>
print(isinstance(my_bool, bool))    # Output: True

my_str = 'hello'
print(type(my_str))                 # Output: <class 'str'>
print(isinstance(my_str, str))      # Output: True
  • type() returns the type of an object.
  • isinstance() checks if an object is an instance of a specified class, returning True or False.

Converting Values to Booleans Using bool()

The bool() constructor converts other values to their boolean equivalents (either True or False).

print(bool('hello'))    # Output: True
print(bool(0))          # Output: False

Formatting Boolean Output

For more customized output, format boolean values as strings before printing. You can convert them to lowercase strings using .lower():

my_bool = True
print(f'{my_bool}'.lower())  # Output: true

Converting Booleans to Integers

To get the integer representation of a boolean, use the int() constructor:

print(int(True))     # Output: 1
print(int(False))    # Output: 0

Converting Integers to Booleans

You can convert integers to booleans using the bool() constructor. Note that 0 will convert to False, and any other number converts to True.

print(bool(1))  # Output: True
print(bool(0))  # Output: False

Using print() with Multiple Arguments

The print() function accepts multiple comma-separated arguments, which are then printed separated by a space by default.

print('is subscribed:', True)           # Output: is subscribed: True
print('is subscribed:', True, sep='')   # Output: is subscribed: True

You can control the separator by using the sep argument in the print function.

Navigation