这是我的代码。当用户输入除1或2以外的任何内容时,为什么我的'else:mainError()'不能执行?例如。 @或上面的任意数字3
print("Welcome to the quiz")
print("Would you like to login with an existing account or register for a new account?")
class validation(Exception):
def __init__(self, error):
self.error = error
def printError(self):
print ("Error: {} ".format(self.error))
def mainError():
try:
raise validation('Please enter a valid input')
except validation as e:
e.printError()
def login():
print ("yet to be made")
def register():
print ("yet to be made")
while True:
options = ["Login", "Register"]
print("Please, choose one of the following options")
num_of_options = len(options)
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
print("You chose to " + options[uchoice - 1])
if uchoice == 1:
login()
break
elif uchoice == 2:
register()
break
else:
mainError()
如果我输入 'A',它与此错误出现:
line 35, in <module>
uchoice = int(input("? "))
ValueError: invalid literal for int() with base 10: 'a'
如果我在上面输入2的数,如 '3':
line 36, in <module>
print("You chose to " + options[uchoice - 1])
IndexError: list index out of range
我怎样才能请确保如果用户输入除1或2以外的任何内容,它将执行我的其他命令,它会在其中调用我的mainError()方法,该方法包含我的例外程序将显示给我的用户的异常。
我已经做了,但现在如果他们输入一个号码错误将只显示给用户大于2 –
我该如何设置,以便在用户输入或@时显示错误? –
这个你需要用try/check来检查你从用户得到的值,或者你可以使用字符串作为用户输入,并在输入之后进行cast/validate以避免这种情况。 –