SEP- AIA

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 . . .

 
  
 
  5. Write a program to demonstrate the AND Gate logic using a Perceptron or simple condition-based
learning.

# 5. Python Program to Demonstrate AND Gate Using Perceptron

## Program

```python id="x7k31p"
# AND Gate using Perceptron

# Input values for AND gate
X = [
    [0, 0],
    [0, 1],
    [1, 0],
    [1, 1]
]

# Expected output
y = [0, 0, 0, 1]

# Initialize weights and bias
w1 = 0
w2 = 0
bias = 0

learning_rate = 1

# Train the perceptron
for epoch in range(10):
    for i in range(len(X)):

        # Calculate weighted sum
        total = X[i][0] * w1 + X[i][1] * w2 + bias

        # Activation function
        if total >= 1:
            prediction = 1
        else:
            prediction = 0

        # Calculate error
        error = y[i] - prediction

        # Update weights and bias
        w1 = w1 + learning_rate * error * X[i][0]
        w2 = w2 + learning_rate * error * X[i][1]
        bias = bias + learning_rate * error

# Test the trained perceptron
print("AND Gate Output:")

for inputs in X:
    total = inputs[0] * w1 + inputs[1] * w2 + bias

    if total >= 1:
        output = 1
    else:
        output = 0

    print(inputs, "->", output)
```

## Sample Output

```text id="h5g7z1"
AND Gate Output:
[0, 0] -> 0
[0, 1] -> 0
[1, 0] -> 0
[1, 1] -> 1
```

## Explanation

* The AND gate has two inputs and one output.
* The output is **1 only when both inputs are 1**.
* A perceptron calculates a weighted sum of the inputs.
* If the weighted sum reaches the threshold, the output is `1`; otherwise, it is `0`.
* The weights and bias are updated during training using the perceptron learning rule.

### AND Gate Truth Table

| Input A | Input B | Output |
| ------: | ------: | -----: |
|       0 |       0 |      0 |
|       0 |       1 |      0 |
|       1 |       0 |      0 |
|       1 |       1 |      1 |