I'm learning about Python and am going through the OO-stage where I'm building a set of logic-gate classes.
To make the logic more resilient, I only want the user to be able to enter a value of 0 or 1 for the pin value in my binary class. I've currently done this by implementing a try/except in the getPin function, but I noticed I wasn't able to add something like:
except(ValueError) or (pinVal != 0 and pinVal != 1)
In the same line (you can, but it ignores the logic after the "or"), so I broke out the numeric checks in the else statement afterward.
Is this the best way to do this? Or is there a way to merge these two together? The fact that I have the identical line:
pinVal = self.invalidPinInput(self.getPin, pin)
Gives me some pause.
Full class code is below:
class BinaryGate(LogicGate): def __init__(self,n): super(BinaryGate,self).__init__(n) self.pinA = self.getPinA() self.pinB = self.getPinB() def invalidPinInput(self, method, pin): print("Invalid input, value must be set to 0 or 1. Please enter 0 or 1.") return method(pin) def getPin(self, pin): try: pinVal = int(input("Enter Pin " + pin + " input for gate "+ str(self.getLabel()) +"-->")) except(ValueError): pinVal = self.invalidPinInput(self.getPin, pin) else: if(pinVal != 0 and pinVal != 1): pinVal = self.invalidPinInput(self.getPin, pin) return pinVal def getPinA(self): return self.getPin("A") def getPinB(self): return self.getPin("B")