← Back to Chapters

Python Boolean Exercises

? Python Boolean Exercises

? Quick Overview

In Python, Boolean values represent truth: True or False. They are used in conditions, comparisons, and control flow to decide what a program should do next.

? Key Concepts

  • Boolean values: True and False (case-sensitive).
  • Boolean operators: and, or, and not to combine or invert conditions.
  • Comparisons: expressions like x < y, x == y, x != y return Booleans.
  • Control flow: Booleans are heavily used in if, elif, and else statements.

? Syntax and Theory

Python has two built-in Boolean constants: True and False. They are capitalized and internally behave like the integers 1 and 0, but are primarily used for logical decisions.

  • andboth conditions must be True.
  • orat least one condition must be True.
  • not → inverts a Boolean value.

Comparison operators such as <, >, ==, and != evaluate to Booleans and are often combined with Boolean operators to build more complex conditions.

? Code Examples

?️ Boolean Values: True and False
is_sunny = True
is_raining = False

print(is_sunny)   # True
print(is_raining) # False
⚙️ Boolean Operators: and, or, not
a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False
? Using Booleans in if Conditions
is_logged_in = True  # Boolean flag indicating login status

if is_logged_in:  # If the user is logged in
    print("Welcome!")  # Greet the user
else:  # If the user is not logged in
    print("Please log in.")  # Ask the user to log in
? Boolean Expressions with Comparisons
x = 10
y = 20

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

? Live Output and Explanation

? What these programs do

  • In the Boolean values example, Python simply prints the values stored in is_sunny and is_raining: True and False.
  • In the Boolean operators example:
    • a and b is False because both must be True.
    • a or b is True because at least one is True.
    • not a is False because a is True.
  • In the if statement example, since is_logged_in is True, the program prints "Welcome!".
  • In the comparison example:
    • x < yTrue because 10 is less than 20.
    • x == yFalse because 10 is not equal to 20.
    • x != yTrue because 10 is not equal to 20.

? Tips and Best Practices

  • Remember that True and False are case-sensitive in Python.
  • Use Boolean operators to combine multiple conditions efficiently instead of deeply nested if statements.
  • Boolean values are often returned by comparison operators like <, >, ==, and !=.
  • Do not use lowercase true or false — they will cause a NameError.
  • In Python, use the keywords and, or, and not (not &&, ||, or !).

? Try It Yourself

  • Write a program that checks if a number is positive and even using Boolean expressions.
  • Write a program to print "Adult" if age >= 18 and "Minor" otherwise.
  • Create a program that uses not to reverse a Boolean value and print the result.