Skip to main content

Introduction to Python Booleans

Python Booleans

The bool data type represents Boolean values, which can have one of two possible states: True or False.

Booleans are used for logical operations, comparisons, and conditional statements.

Here are some examples of Boolean values and their usage in Python:

is_raining = True
has_passed_exam = False

Boolean values are commonly used in conditional statements, such as if statements, to control the flow of the program based on certain conditions.

As an example:

x = 5
y = 10

if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")

In this example:

  • The condition x < y is evaluated, and based on the result (True or False), the corresponding code block is executed.

Boolean values can also be obtained through comparison operators, which allow you to compare two values and return a Boolean result.

Here are some comparison operators in Python:

  • ==: Equal to
  • !=: Not equal to
  • <: Less than
  • >: Greater than
  • <=: Less than or equal to
  • >=: Greater than or equal to
x = 5
y = 10

print(x == y) # Output: False
print(x < y) # Output: True
print(x != y) # Output: True

Boolean values can be combined using logical operators to create more complex conditions.

The logical operators in Python are:

  • and: Returns True if both operands are True
  • or: Returns True if at least one of the operands is True
  • not: Returns the opposite Boolean value of the operand
is_sunny = True
temperature = 25

if is_sunny and temperature > 30:
print("It's hot and sunny")
elif is_sunny or temperature > 30:
print("It's either hot or sunny")
else:
print("It's neither hot nor sunny")

In this example:

  • The program checks if it's hot and sunny, or if it's either hot or sunny, based on the conditions evaluated with logical operators.

Boolean Conversion

You can explicitly convert values to Boolean using the bool() function.

The bool() function returns False for falsy values and True for truthy values.

print(bool(0))  # Output: False
print(bool(10)) # Output: True
print(bool("")) # Output: False
print(bool("Hello")) # Output: True