try:
psl = int(input("Source Position - Line Number: "))
psc = int(input("Source Position - Column Number: "))
except ValueError:
print("Error: you have to enter an integer between 0 and 7 inclusivelyn")
continue
在那一小段代码中,玩家必须输入两个介于 0 和 7 之间的整数(包括 0 和 7(,分别对应于一行和一列。我意识到如果我输入9
,则永远不会触发异常。如果整数不在 [0, 7] 范围内,如何触发异常?
如果要引发异常,请使用raise
关键字。
例如:
try:
psl = int(input("Source Position - Line Number: "))
psc = int(input("Source Position - Column Number: "))
if not (0 <= psl <= 7 and 0 <= psc <= 7):
raise ValueError # <==== here
self.pss = Pos(psl, psc)
validation = self.validation_ps(self.pss)
except ValueError:
print("Error: you have to enter an integer between 0 and 7 inclusivelyn")
continue
您还可以为其提供关联的错误消息:
raise ValueError("you entered a bad number")
然后要利用它,您需要在except
块中的变量(通常为exc
(中捕获异常,例如:
except ValueError as exc:
print("the error was ", exc)
# ...
你可以有一个这样的语句:
if not (psl in range(0,8) and psc in range(0,8)):
raise ValueError('Error: you have to enter an integer between 0 and 7 inclusivelyn')
您可以考虑使用断言来处理逻辑,同时保留非数字输入的异常。
try:
psl = int(input("Source Position - Line Number: "))
psc = int(input("Source Position - Column Number: "))
assert (0 <= psl <= 7 and 0 <= psc <= 7), 'Please enter a values between 0 and 7'
except ValueError:
print('Please enter a number!)
是你试图做这样的事情:
while True:
psl = input("Source Position - Line Number: ")
psc = input("Source Position - Column Number: ")
if all([psl.isdigit(), psc.isdigit()]):
if all([7 >= int(psl) >= 0, 7 >= int(psc) >= 0]):
break
print("Error: you have to enter an integer between 0 and 7 inclusivelyn")
self.pss = Pos(psl, psc)
validation = self.validation_ps(self.pss)