122k views
4 votes
Write a program in Python representing 7 logic gates:

AND
NAND
OR
NOR
XOR
XNOR
NOT
Accept (only) two inputs to create all outputs.
Use the if statement to perform the Boolean logic.
Only accept numeric input.
If a number is greater than 0 treat it as a 1.
Specify in your output and in the beginning of the code (through print statements) which gate the code represents.
Comment your code.

User Galian
by
5.4k points

1 Answer

6 votes

Answer:

The program in python is as follows:

a = int(input("A: "))

b = int(input("B: "))

if a != 0:

a= 1

if b != 0:

b = 1

print("A AND B",end =" ")

if a == b == 1:

print("True")

else:

print("False")

print("A NAND B",end =" ")

if a == 0 or b == 0:

print("True")

else:

print("False")

print("A OR B",end =" ")

if a == 1 or b == 1:

print("True")

else:

print("False")

print("A NOR B",end =" ")

if a == 1 or b == 1:

print("False")

else:

print("True")

print("A XOR B",end =" ")

if a != b:

print("True")

else:

print("False")

print("A XNOR b",end =" ")

if a == b:

print("True")

else:

print("False")

print("NOT A",end =" ")

if a == 1:

print("False")

else:

print("True")

print("NOT B",end =" ")

if b == 1:

print("False")

else:

print("True")

Step-by-step explanation:

These get inputs for A and B

a = int(input("A: "))

b = int(input("B: "))

a and b are set to 1 for all inputs other than 0

if a != 0:

a= 1

if b != 0:

b = 1

This prints the AND header

print("A AND B",end =" ")

AND is true if only A and B are 1

if a == b == 1:

print("True")

else:

print("False")

This prints the NAND header

print("A NAND B",end =" ")

NAND is true if one of A or B is 0

if a == 0 or b == 0:

print("True")

else:

print("False")

This prints the OR header

print("A OR B",end =" ")

OR is true if one of A or B is 1

if a == 1 or b == 1:

print("True")

else:

print("False")

This prints the NOR header

print("A NOR B",end =" ")

NOR is false if one of A or B is 1

if a == 1 or b == 1:

print("False")

else:

print("True")

This prints the XOR header

print("A XOR B",end =" ")

XOR is true if A and B are not equal

if a != b:

print("True")

else:

print("False")

This prints the XNOR header

print("A XNOR b",end =" ")

XNOR is true if a equals b

if a == b:

print("True")

else:

print("False")

This prints NOT header for A

print("NOT A",end =" ")

This prints the opposite of the input

if a == 1:

print("False")

else:

print("True")

This prints NOT header for B

print("NOT B",end =" ")

This prints the opposite of the input

if b == 1:

print("False")

else:

print("True")

User Prodigle
by
5.4k points