【发布时间】:2021-11-02 19:57:20
【问题描述】:
我是一个初学者,我正在编写一个接受用户输入的应用程序。我正在使用类,对于输入验证,我为异常编写了下面的代码。当我尝试检查无效输入时,它不起作用。拜托,有人告诉我该怎么做:)
class Game:
def __init__(self, packs_purchase, dice_purchase, board_games_purchase):
self.packs_purchase = packs_purchase
self.dice_purchase = dice_purchase
self.board_games_purchase = board_games_purchase
def validate_inputs(self,packs_purchase, dice_purchase, board_games_purchase):
all_inputs = zip(packs_purchase, dice_purchase, board_games_purchase)
#validate length of inputs to be same
if not len(packs_purchase) == len(dice_purchase) == len(board_games_purchase):
raise ValueError("Invalid input- customer order size must be equal")
for pack, dice, board in all_inputs:
#validate each list has whole numerical input
if not isinstance(pack, int) or not isinstance(dice, int) or not isinstance(board, int):
raise TypeError("Invalid input- please check input must be integer")
#validate all inputes to be positive integers
if pack < 0 or dice < 0 or board < 0:
raise Exception("Invalid input- all inputs must be positive integer")
【问题讨论】:
-
你遇到了什么错误?
-
它发生在哪里?
-
问题是,我的异常不会因无效输入而引发
-
你刚刚定义了方法 validate_inputs() 但你从来没有真正调用它
-
天哪!你是对的
标签: python validation exception user-input