# Logic Gates in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about Logic Gates in Python. Let’s look at each of the logic gates in Python in detail with some easy examples.

All of us are quite familiar while implementing logic gates in the processing of electrical signals and are widely used in the electrical and electronics industry. They are used in the diodes and transistors so that we can design by proper alignment of these electronic devices. In this article we will learn about the implementation of some basic gates ‘and‘, ‘or‘ ,’not‘ , ‘nand‘ ,’nor‘ in Python 3.x or earlier.

These gates can be implemented by using user-defined functions designed in accordance with that of the truth table associated with the respective gate.

## Construction of And Gate in Python

### Example

def AND (a, b):
if a == 1 and b == 1:
return True
else:
return False

# main function
if __name__=='__main__':
print(AND(0,0))
print(AND(1,0))
print(AND(0,1))
print(AND(1,1))

### Output

False
False
False
True

## Construction of Or Gate in Python

### Example

def OR(a, b):
if a == 1:
return True
elif b == 1:
return True
else:
return False
# main function
if __name__=='__main__':
print(OR(0,0))
print(OR(1,0))
print(OR(0,1))
print(OR(1,1))

## OUTPUT

False
True
True
True

## Example

def NOT(a):
if(a == 0):
return 1
elif(a == 1):
return 0

# main function
if __name__=='__main__':
print(OR(0))
print(OR(1))

### Output

True
False

## Construction of Nand Gate in Python

### Example

def NAND (a, b):
if a == 1 and b == 1:
return False
else:
return True

# main function
if __name__=='__main__':
print(NAND(0,0))
print(NAND(1,0))
print(NAND(0,1))
print(NAND(1,1))

### Output

True
True
True
False

## Construction of Nor Gate in Python

### Example

def NOR(a, b):
if(a == 0) and (b == 0):
return True
elif(a == 0) and (b == 1):
return False
elif(a == 1) and (b == 0):
return False
elif(a == 1) and (b == 1):
return False

# main function
if __name__=='__main__':
print(NOR(0,0))
print(NOR(1,0))
print(NOR(0,1))
print(NOR(1,1))

### Output

True
False
False
False

## Conclusion

In this article, we learned how to implement logic gates in Python 3.x. Or earlier. We also learned about two universal gates i.e. NAND and NOR gates.

Published on 07-Aug-2019 08:26:41