我有以下方法,我用它來獲取用戶的輸入并通過例外處理它,直到它們滿足標準。
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
這就是我所說的方式
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)
這似乎不適用于輸入的任何型別,無論它是負數還是與我指定的匹配。
這里有任何幫助嗎?我知道我必須接近。
例如:
當我運行add_item_num = self.enter_data("What is the new items #?\n", int)并輸入 1 時,我得到:“那不是 int!”,即使輸入是 int 并且是正數,所以它不應該觸發if isinstance(...)陳述句
uj5u.com熱心網友回復:
這歸結為一個True or False and False = True問題。沒有括號,這是這樣執行的
or(True, and(False,False))
第一個值立即回傳,其他值不計算。
你的想法很完美,你只需要加上括號
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517465.html
