Book Free Trial

Curriculum

Boolean in Python

Subject: ProgrammingCourse: Coding In PythonAges: Primary, Junior

Theory

The bool Data Type in Python

Comparison operators return a special boolean type: bool. A boolean value can be either True or False.

Boolean values

  • True — logical truth.
  • False — logical falsehood.

Example:

x = 5
y = 3

result = x > y print(result) # True print(type(result)) # <class 'bool'>

Conversion between bool and int

  • True converts to 1.
  • False converts to 0.
  • 0 converts to False.
  • Any nonzero integer converts to True.
print(int(True))   # 1
print(int(False))  # 0

print(bool(0)) # False print(bool(42)) # True

Conversion between bool and str

  • An empty string "" converts to False.
  • Any non-empty string converts to True.
print(bool(""))       # False
print(bool("Hello"))  # True
print(bool("0"))      # True  # non-empty string is always True

When booleans are used

  • In if, elif, while conditions.
  • Returned by comparison and logical operators (<, ==, !=, and, or, not).
  • As flags to represent yes/no, on/off, success/failure states in programs.

Quick practice

  1. Check if the square of a number is greater than 50, and print the boolean result.
  2. Convert True and False to integers and print them.
  3. Ask the user for a string and print whether it is empty (False) or not (True).
Show sample solutions
# 1) Square greater than 50?
x = int(input())
print(x * x > 50)

2) Convert booleans to integers



print(int(True), int(False))



3) Check empty string

s = input("Enter text: ") print(bool(s))

Key takeaways: bool is a basic type with only two values: True and False. It plays a central role in controlling program flow, and Python offers straightforward conversions between booleans and other types.