Boolean logic & truth tables · 布尔逻辑与真值表
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Boolean values
- A Boolean value is either
TrueorFalse. - A condition such as
age >= 18produces a Boolean. - Computers build everything from these two values.
中文
布尔值
- 布尔(Boolean)值要么是
True,要么是False。 - 像
age >= 18这样的条件会得到一个布尔值。 - 计算机用这两个值搭建出一切。
English
AND, OR, NOT
andis True only when both sides are True.oris True when at least one side is True.notflips True to False, and False to True.
中文
AND、OR、NOT
and(与)只有当两边都为真时才为真。or(或)当至少一边为真时就为真。not(非)把真变假、把假变真。
print(True and False) # False
print(True or False) # True
print(not True) # False
English
A truth table
- A truth table lists every possible input and its output.
- Two inputs (A, B) give four rows: 00, 01, 10, 11.
中文
真值表
- 真值表(truth table)列出每一种可能的输入及其输出。
- 两个输入(A、B)有四行:00、01、10、11。
Explore · 探索
Truth table — try every input · 真值表 —— 试试每种输入
and is true only when both · 两者 are true; or when at least one is. · and 只有两边都为真时才为真;or 只要至少一边为真。
English
Build a truth table with loops
- A nested loop over
False, Truewalks through all the combinations.
中文
用循环生成真值表
- 在
False, True上做嵌套循环,就能走遍所有组合。
for a in [False, True]:
for b in [False, True]:
print(a, b, a and b)
English
More gates: NAND, NOR, XOR
- NAND is
not (a and b); NOR isnot (a or b). - XOR is True when the inputs are different:
a != b.
中文
更多门:NAND、NOR、XOR
- NAND 是
not (a and b);NOR 是not (a or b)。 - XOR(异或)在输入不同时为真:
a != b。
English
In the exam: logic gates
- Know the gates NOT, AND, OR, NAND, NOR, XOR and their truth tables.
中文
在考试里:逻辑门
- 记住这些门:NOT、AND、OR、NAND、NOR、XOR,以及它们的真值表。
X ← A AND B
Y ← NOT (A OR B)
English
Common mistakes
ANDis true only when both inputs are true;ORis true when at least one is.NOTflips the value.- A truth table lists every combination of the inputs.
中文
常见错误
AND只有两个输入都为真时才为真;OR至少一个为真就为真。NOT把值取反。- 真值表列出输入的每一种组合。
English
Now you try
- Each function returns the gate's Boolean output.
- Press Check answer to test your code.
中文
现在轮到你
- 每个函数返回对应逻辑门的布尔输出。
- 按检查答案来测试你的代码。
Write AND_gate(a, b) that returns True only when both · 两者 inputs are True. · 写一个 AND_gate(a, b),只有当两个输入都为 True 时才返回 True。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write XOR_gate(a, b) that returns True when the two inputs are different, and False when they are the same. · 写一个 XOR_gate(a, b),当两个输入不同时返回 True,相同时返回 False。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write NAND_gate(a, b) that gives the opposite of AND: True unless both inputs are True. Use not (a and b). · 写一个 NAND_gate(a, b),给出 AND 的相反结果:除非两个输入都为 True,否则返回 True。用 not (a and b)。
Click Run to see the output here. · 点击“运行”查看此处输出。