繁体   English   中英

当用户输入1或2之外的任何其他值时,为什么我的“ else:mainError()”未执行? 例如@或a或大于3的任何数字

[英]Why is my 'else: mainError()' not executing when a user inputs anything other than 1 or 2? E.g. @ or a or any number above 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,它将执行我的else命令,并在其中调用我的mainError()方法,该方法包含程序将显示给用户的异常。

出现异常是因为您没有要在消息中打印的options元素

 print("You chose to " + options[uchoice - 1])

在这里,您尝试获取不存在的选项[a]或选项[3]。 将此打印仅放置在具有相关选项的if / else内,将另一张打印放入不包含相关选项的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>: ...而增加开销, try: ... except <error>: ...语句,因此在最佳情况下,您将对每个类似的条件使用条件检查:

if (uchoice - 1) > len(options):
    <handling for when the user inputs out-of-range integer>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM