Zone Of Makos

Menu icon

Boolean in Python

In Python, bool is a built-in data type that represents a boolean value. A boolean value can be either True or False . Boolean values are used in conditional statements to control the flow of a program.

Boolean Values

Boolean values are created using the keywords True and False :


# Example of boolean values
x = True
y = False
print(x) # Output: True
print(y) # Output: False

Note that boolean values are case-sensitive - you must use uppercase letters.

Boolean Operators

Python has three built-in boolean operators:

  • and : Returns True if both operands are True , otherwise returns False .
  • or : Returns True if either operand is True , otherwise returns False .
  • not : Returns True if the operand is False , otherwise returns False .

Here are some examples:


# Examples of boolean operators
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False

Boolean operators can be combined to create complex boolean expressions:


# Example of a complex boolean expression
x = 5
print(x > 0 and x < 10) # Output: True

Here, the expression x > 0 and x < 10 is evaluated as True because x is greater than 0 and less than 10.

Boolean Conversion

Many Python objects can be converted to boolean values. Here's how it works:

  • Objects that are considered empty are converted to False . Examples of empty objects include empty lists, empty strings, and the value None .
  • Objects that are not empty are converted to True .

Here are some examples:


# Examples of boolean conversion
x = [] # empty list
y = "hello" # non-empty string
z = None # None value
print(bool(x)) # Output: False
print(bool(y)) # Output: True
print(bool(z)) # Output: False

That's a brief introduction to boolean values in Python. By understandingthe basics of boolean values and operators, you can create complex conditional statements to control the flow of your Python programs.