πŸ–₯️
Berkeley CS61A: Notes
  • 🌍Hello, World!
  • πŸ’­Learn to Think Like Your Computer
  • Building Blocks
    • ❗Expressions in Python
      • ℹ️Mathematical Statements
      • 🀫Variables
      • πŸ‘Data Types in Python
    • 🚧Introduction to Functions
      • πŸƒβ€β™€οΈHow Python Executes a Function Call
      • 🚱Functions that Don't Return Anything
    • 🌊Control Flow
      • ⁉️What is an if statement?
      • πŸ’ΎWhat is a Loop?
      • 🚨What are Logical Operators?
        • πŸ˜–Logical Operators, Seemingly Illogical Behavior
      • 🚰How Does Control Flow?
    • ⚑Higher-Order Functions
      • ⏸️What are Higher-Order Functions Used For?
      • πŸ‘†Self-Reference
    • πŸ‘ΎEnvironments and Scope
      • πŸ–ŠοΈHow to Make Environment Diagrams
  • STRUCTURES OF DATA
    • ➰Recursion
      • πŸ«€Anatomy of Recursion
      • β›½Recursive Leap of Faith
    • πŸŽ„Tree Recursion
      • ⬇️The Use It/Lose It Principle
    • πŸ“€Iterables
      • βœ‚οΈList Slicing
      • πŸ’€Deep Lists
      • πŸŒ‹Iterable Functions
      • πŸ’½List Comprehensions
    • πŸ™ˆAbstraction
    • Trees
    • Linked Lists
    • Iterators and Generators
    • Efficiency
  • Extra Topics
    • 🎭Errors and their Types
      • 🏹Error vs Exception
      • πŸ”™What is Backtracing?
    • 🚑How the Terminal and the File are Different
    • 🍬Decorators
  • Debugging Tools
    • πŸ–¨οΈDebugging with Print Statements
    • πŸ›Debugging with the Debugger
Powered by GitBook
On this page

Was this helpful?

  1. Building Blocks
  2. Control Flow
  3. What are Logical Operators?

Logical Operators, Seemingly Illogical Behavior

?!?!

And now an example that contains both and and or:

>>> 1 or 0 and 1/0 or 2

And this statement gets tricky to comprehend! Here's the core idea: the and operator takes precedence over the or operator.

In simpler English, what this means is that the statement looks something like this:

>>> 1 or (0 and 1/0) or 2

This statement first evaluates 1, finds it to be a truthy value, and immediately returns it. This is why the 1/0 doesn't throw an error.

Try this one yourself:

>>> 0 or None and 1/0 or 2

Now that you've given this a shot, let's walk through it together!

>>> 0 or None and 1/0 or 2
>>> 0 or (None and 1/0) or 2

First, the or statement evaluates 0. Finding it to be a false-y value, it keeps going. It evaluates (None and 1/0) next. In this, the and finds None to be the first false-y value, and immediately returns it. The outer or statements sees None as the next value, and keeps going. It therefore returns 2, the first truth-y value it finds!

PreviousWhat are Logical Operators?NextHow Does Control Flow?

Last updated 3 years ago

Was this helpful?

🌊
🚨
πŸ˜–