Python Booleans

Booleans represent one of two values: Boolean values are often used to make decisions and control the flow of a program. Boolean Values Example: Output: Boolean Variables You can store boolean values in variables. Example: Output: Evaluate Expressions Many expressions return a boolean value. Example: Output: Using bool() The bool() function evaluates a value and […]

2 mins read Lesson 2 of 43 5% through track

Booleans represent one of two values:

  • True
  • False

Boolean values are often used to make decisions and control the flow of a program.

Boolean Values

Example:

print(True)
print(False)

Output:

True
False

Boolean Variables

You can store boolean values in variables.

Example:

is_logged_in = True
is_admin = False

print(is_logged_in)
print(is_admin)

Output:

True
False

Evaluate Expressions

Many expressions return a boolean value.

Example:

print(10 > 5)
print(10 == 5)
print(10 < 5)

Output:

True
False
False

Using bool()

The bool() function evaluates a value and returns True or False.

Example:

print(bool("Hello"))
print(bool(15))

Output:

True
True

Most Values are True

Almost any value is evaluated as True if it contains data.

Example:

print(bool("Python"))
print(bool(100))
print(bool(["Apple", "Banana"]))

Output:

True
True
True

Some Values are False

The following values evaluate to False:

  • False
  • None
  • 0
  • 0.0
  • "" (empty string)
  • [] (empty list)
  • () (empty tuple)
  • {} (empty dictionary)

Example:

print(bool(False))
print(bool(0))
print(bool(""))
print(bool([]))

Output:

False
False
False
False

Boolean in Conditions

Boolean values are commonly used with if statements.

Example:

age = 18

if age >= 18:
    print("You are an adult")

Output:

You are an adult

Functions Returning Boolean Values

Functions can return boolean values.

Example:

def is_adult(age):
    return age >= 18

print(is_adult(20))
print(is_adult(15))

Output:

True
False

Practical Example

Check if a user can access a page:

is_logged_in = True

if is_logged_in:
    print("Access Granted")
else:
    print("Access Denied")

Output:

Access Granted

Boolean Operators

Python provides logical operators for working with boolean values.

OperatorDescription
andReturns True if both conditions are true
orReturns True if at least one condition is true
notReverses the result

Example:

x = 10

print(x > 5 and x < 20)
print(x > 20 or x < 20)
print(not(x > 20))

Output:

True
True
True

Summary

  • Booleans have only two values: True and False.
  • Comparison operations return boolean values.
  • The bool() function converts values to booleans.
  • Empty values such as 0, "", and [] evaluate to False.
  • Boolean values are commonly used in conditions and loops.
  • Logical operators include and, or, and not.