Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.5.3 Booleans Hack (P2)
Student led teaching on Booleans. Learn how booleans are used in decision-making with logical operators.
Homework Hack
Create a Logic Gates Simulator in Python and Java this demonstrates how different logical operations (AND, OR, NOT, NAND, NOR, XOR) work with various inputs. This can visually represent how truth tables function.
Logic Gate Simulator in Python
def AND(A, B):
return A and B
def OR(A, B):
return A or B
def NOT(A):
return not A
print("A B | AND | OR | NOT A")
print("---------------------------")
for A in [True, False]:
for B in [True, False]:
print(f"{A:<5} {B:<5} | {AND(A, B):<4} | {OR(A, B):<3} | {NOT(A)}")
A B | AND | OR | NOT A
---------------------------
1 1 | 1 | 1 | False
1 0 | 0 | 1 | False
0 1 | 0 | 1 | True
0 0 | 0 | 0 | True
Logic Gate Simulator in Javascript
%%javascript
// Define logic gate functions
function AND(A, B) {
return A && B;
}
function OR(A, B) {
return A || B;
}
function NOT(A) {
return !A;
}
function NAND(A, B) {
return !(A && B);
}
function NOR(A, B) {
return !(A || B);
}
function XOR(A, B) {
return A !== B;
}
// Display the results of the logic gates
function displayGateOperations(A, B) {
console.log("A: " + A + ", B: " + B);
console.log("AND: " + AND(A, B));
console.log("OR: " + OR(A, B));
console.log("NOT A: " + NOT(A));
console.log("NAND: " + NAND(A, B));
console.log("NOR: " + NOR(A, B));
console.log("XOR: " + XOR(A, B));
console.log("-----------------------------");
}
// Main logic gate simulator function
function logicGateSimulator() {
console.log("Logic Gate Simulator");
console.log("Enter 'exit' to quit");
while (true) {
let A_input = prompt("Enter value for A (true/false): ").trim();
if (A_input.toLowerCase() === "exit") {
break;
}
let B_input = prompt("Enter value for B (true/false): ").trim();
if (B_input.toLowerCase() === "exit") {
break;
}
// Convert inputs to boolean
let A = (A_input.toLowerCase() === 'true');
let B = (B_input.toLowerCase() === 'true');
// Display the results
displayGateOperations(A, B);
}
}
// Run the logic gate simulator
logicGateSimulator();
<IPython.core.display.Javascript object>