Boolean Logic in Python
Master boolean values and logical operations in Python programming.
Boolean logic is the foundation of decision-making in programming. Every if statement, every loop condition, and every comparison relies on boolean values. Understanding how True and False work, along with logical operators like and, or, and not, is essential for writing effective Python code. This exercise will teach you to work confidently with boolean expressions.
📚 Concepts & Theory
Boolean Values
Python has two boolean values: True and False (note the capital letters).
is_active = True
is_complete = False
Comparison Operators
These operators return boolean values:
5 > 3 # True
5 < 3 # False
5 == 5 # True
5 != 3 # True
5 >= 5 # True
5 <= 4 # False
Logical Operators
and- Both must be Trueor- At least one must be Truenot- Inverts the value
True and True # True
True and False # False
True or False # True
not True # False
Truthy and Falsy Values
Some values act as False:
False,None,0,"",[],{}
🎯 Your Challenge
Create two boolean variables: `has_ticket` set to True and `is_vip` set to False. Then create a variable `can_enter` that is True only if the person has a ticket OR is a VIP.
📝 Starter Code
# Create boolean variables
has_ticket =
is_vip =
# Can enter if has ticket OR is VIP
can_enter =
- Boolean values in Python are True and False with capital letters
- The or operator returns True if at least one operand is True
- You can combine conditions without parentheses for simple expressions
Solution
has_ticket = True
is_vip = False
can_enter = has_ticket or is_vip
Explanation
We set has_ticket to True and is_vip to False. Using the or operator, can_enter will be True if either condition is True. Since has_ticket is True, can_enter becomes True.
⚠️ Common Mistakes to Avoid
- Using lowercase true/false instead of True/False
- Confusing and with or
- Using = instead of == for comparison
- Not understanding operator precedence