Logical operators: and, or, not
Real-world rules often require checking multiple conditions at once: 'You must be at least 120cm tall AND have a ticket, OR be accompanied by an adult.' Logical operators make this possible.
- Combine conditions using the 'and' operator (both must be True).
- Use the 'or' operator (at least one must be True).
- Invert conditions cleanly using the 'not' operator.
Boolean algebra with and, or, not, and operator precedence.
Logical operators combine multiple conditions. Precedence order: not takes precedence over and, which takes precedence over or. Use parentheses to eliminate ambiguity.
Roller-Coaster ticketing logic
You can only ride if height >= 120cm. Ticket price depends on age: child (<12: $5), youth (12-18: $7), adult (>18: $12). Plus an optional photo pass for $3.
Memory Trace: Multi-Tier Condition Evaluation
Step through height validation, age price bracket, and photo surcharge.
| Variable | Value in Memory | Data Type |
|---|---|---|
| height | 135 | int |
135cm stored.
height = 135🔧 Missing Parentheses in Logic Precedence
A rollercoaster admission check let riders in without a pass because OR evaluated with unexpected precedence.
Predict The Output (2 Questions)
Your lightbulb moment
The key takeaway
`and`, `or`, and `not` allow compounding logical conditions to model real-world business and game rules.
Make it yours
Try changing the age to 25 and rerun to verify that the adult tier ($12 + $3 = $15) runs automatically.
Try editing the code in the playground above in Python, JavaScript, Java, or C++, and use the step-by-step Dry-Run Table to inspect how variables mutate in memory. If you get stuck, click the 🤖 AI Doubt Solver button on your screen for instant explanations!