Skip to content

Commit ae11088

Browse files
Update and_gate.py
Add Input Validation and Interactive Mode to N-Input AND Gate. This pull request adds input validation and an interactive mode to the N-input AND gate program. It ensures all inputs are limited to binary values (0 or 1) and provides clear error messages for invalid input. Additionally, users can now interactively enter any number of inputs to see the AND gate output calculated in real time, making the program more robust and user-friendly.
1 parent e2a78d4 commit ae11088

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

boolean_algebra/and_gate.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ def and_gate(input_1: int, input_2: int) -> int:
2929
>>> and_gate(1, 1)
3030
1
3131
"""
32+
if input_1 not in (0, 1) or input_2 not in (0, 1):
33+
raise ValueError("Inputs must be 0 or 1")
3234
return int(input_1 and input_2)
3335

3436

@@ -41,10 +43,30 @@ def n_input_and_gate(inputs: list[int]) -> int:
4143
>>> n_input_and_gate([1, 1, 1, 1, 1])
4244
1
4345
"""
46+
if not inputs:
47+
raise ValueError("Input list cannot be empty")
48+
if any(x not in (0, 1) for x in inputs):
49+
raise ValueError("All inputs must be 0 or 1")
4450
return int(all(inputs))
4551

4652

53+
4754
if __name__ == "__main__":
4855
import doctest
4956

5057
doctest.testmod()
58+
print("\n--- N-Input AND Gate Simulator ---")
59+
try:
60+
n = int(input("Enter the number of inputs: "))
61+
inputs = []
62+
for i in range(n):
63+
val = int(input(f"Enter input {i + 1} (0 or 1): "))
64+
if val not in (0, 1):
65+
raise ValueError("Inputs must be 0 or 1")
66+
inputs.append(val)
67+
68+
result = n_input_and_gate(inputs)
69+
print(f"Inputs: {inputs}")
70+
print(f"AND Gate Output: {result}")
71+
except ValueError as e:
72+
print("Error:", e)

0 commit comments

Comments
 (0)