Skip to content

Commit c3b0896

Browse files
committed
Updated the error handling in and_gate.py
1 parent a71618f commit c3b0896

1 file changed

Lines changed: 48 additions & 7 deletions

File tree

boolean_algebra/and_gate.py

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,29 +18,70 @@
1818

1919
def and_gate(input_1: int, input_2: int) -> int:
2020
"""
21-
Calculate AND of the input values
21+
Calculate AND of two binary input values.
2222
2323
>>> and_gate(0, 0)
2424
0
2525
>>> and_gate(0, 1)
2626
0
27-
>>> and_gate(1, 0)
28-
0
2927
>>> and_gate(1, 1)
3028
1
29+
>>> and_gate(2, 1)
30+
Traceback (most recent call last):
31+
...
32+
ValueError: Both inputs must be 0 or 1
33+
>>> and_gate(0, "1")
34+
Traceback (most recent call last):
35+
...
36+
TypeError: Both inputs must be integers
3137
"""
32-
return int(input_1 and input_2)
38+
# Type validation
39+
if not isinstance(input_1, int) or not isinstance(input_2, int):
40+
raise TypeError("Both inputs must be integers")
41+
42+
# Value validation
43+
if input_1 not in (0, 1) or input_2 not in (0, 1):
44+
raise ValueError("Both inputs must be 0 or 1")
45+
46+
return input_1 & input_2
3347

3448

3549
def n_input_and_gate(inputs: list[int]) -> int:
3650
"""
37-
Calculate AND of a list of input values
51+
Calculate AND of a list of binary input values.
3852
39-
>>> n_input_and_gate([1, 0, 1, 1, 0])
40-
0
4153
>>> n_input_and_gate([1, 1, 1, 1, 1])
4254
1
55+
>>> n_input_and_gate([1, 0, 1, 1, 0])
56+
0
57+
>>> n_input_and_gate([])
58+
Traceback (most recent call last):
59+
...
60+
ValueError: Input list cannot be empty
61+
>>> n_input_and_gate([1, 2, 1])
62+
Traceback (most recent call last):
63+
...
64+
ValueError: All inputs in the list must be 0 or 1
65+
>>> n_input_and_gate([1, "1"])
66+
Traceback (most recent call last):
67+
...
68+
TypeError: All inputs in the list must be integers
4369
"""
70+
# Type validation for the list itself
71+
if not isinstance(inputs, list):
72+
raise TypeError("Input must be a list")
73+
74+
# Edge case validation for an empty list
75+
if not inputs:
76+
raise ValueError("Input list cannot be empty")
77+
78+
# Type and value validation for items within the list
79+
for item in inputs:
80+
if not isinstance(item, int):
81+
raise TypeError("All inputs in the list must be integers")
82+
if item not in (0, 1):
83+
raise ValueError("All inputs in the list must be 0 or 1")
84+
4485
return int(all(inputs))
4586

4687

0 commit comments

Comments
 (0)