I have the following method, which I use to take inputs from the user and handle it via exceptions until they fullfill the criteria.
def enter_data(self, message: str, typ: type):
while True:
try:
v = typ(input(message))
if isinstance(v, int) or isinstance(v, float) and v < 0:
raise ValueError
except ValueError:
print(f"Thats not an {typ}! or you have entered a negative")
continue
else:
break
return v
This is the way I call it
def add_item_interaction(self) -> None:
add_item_num = self.enter_data("What is the new items #?\n", int)
add_item_price = self.enter_data("What is the new items price?\n", float)
add_item_quant = self.enter_data("What is the new items quantity?\n", int)
add_name = self.enter_data("What is the new items name?\n", str)
This doesn't seem to work for any type entered, no matter if it is a negative or matches what I specify.
Any Help Here? I know I must be close.
For example:
When I run add_item_num = self.enter_data("What is the new items #?\n", int)
, and input 1, I get: "Thats not an int!", even though the input is an int, and positive, so it should not trigger the if isinstance(...)
statement
CodePudding user response:
This boils down to a True or False and False = True
problem.
Without paranthesis this is executed like this
or(True, and(False,False))
The first value is instantly returned and the others are not evaluated.
Your idea is perfect you just need to add the parantheses
def enter_data(self, message: str, typ: type):
while True:
try:
v = typ(input(message))
if (isinstance(v, int) or isinstance(v, float)) and v < 0:
raise ValueError
except ValueError:
print(f"Thats not an {typ}! or you have entered a negative")
continue
else:
break
return v