当用户输入除1或2以外的任何内容时,为什么我的'else:mainError()'不能执行?例如。 @或上面的任意数字3
问题描述:
这是我的代码。当用户输入除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()方法,该方法包含我的例外程序将显示给我的用户的异常。
答
的异常升高,因为你没有你想的消息
print("You chose to " + options[uchoice - 1])
在这里,在打印选项元素你正在试图获得选项[A]或期权[3]这不存在。 仅将此打印放在具有相关选项的if/else中,而将另一个打印放在其他没有的选项中。 事情是这样的:
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
if uchoice == 1:
print("You chose to " + options[uchoice - 1])
login()
break
elif uchoice == 2:
print("You chose to " + options[uchoice - 1])
register()
break
else:
mainError()
答
uchoice = int(input("? "))
那么这里你必须做的像一些错误检查代码:
try:
uchoice = int(input("? "))
except ValueError:
<handling for when the user doesn't input an integer [0-9]+>
然后,当用户输入一个指数,这不是处理溢出在列表范围内:
try:
options[uchoice - 1]
except IndexError:
<handling for when the user inputs out-of-range integer>
当然这增加了开销,因为try: ... except <error>: ...
声明所以在最优化的情况下,你会使用条件检查每个这样的事情:
if (uchoice - 1) > len(options):
<handling for when the user inputs out-of-range integer>
+0
它工作成功!谢谢。 –
我已经做了,但现在如果他们输入一个号码错误将只显示给用户大于2 –
我该如何设置,以便在用户输入或@时显示错误? –
这个你需要用try/check来检查你从用户得到的值,或者你可以使用字符串作为用户输入,并在输入之后进行cast/validate以避免这种情况。 –