Logic and bit operations

Module 3 · Logic and bit operations · Lesson 2 of 6

Logical values vs. single bits

Python actually has two families of “and / or / not”, and they work at different levels. It's worth pinning the difference down now, because mixing them up is a subtle source of bugs.

Same word, two levels
Logical — whole values
True and TrueTrue
Bitwise — column by column
5 =
101
3 =
011
& =
001
= 1

The logical operators — and, or, not — treat each side as a single True/False value. That's what you use in if conditions.

The bitwise operators — &, |, ~ — go deeper. They line two numbers up in binary and apply the logic to each pair of bits independently. So 5 & 3 isn't a yes/no answer — it's a whole new number, built bit by bit.

Run it yourselfruns in your browser · Python
main.py

The rule of thumb: use the words (and, or) for conditions and True/False, and the symbols (&, |) for working with the bits of integers — which is exactly where we're heading next.