简体   繁体   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

This is my code. 这是我的代码。

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()

If I enter 'a', it comes up with this error: 如果输入“ a”,则会出现此错误:

line 35, in <module>
uchoice = int(input("? "))
ValueError: invalid literal for int() with base 10: 'a'

If I enter a number above 2 like '3': 如果我输入的数字大于2,例如“ 3”:

line 36, in <module>
print("You chose to " + options[uchoice - 1])
IndexError: list index out of range

How can I make sure that if a user enters anything other than 1 or 2, it executes my else commands where it calls my mainError() method which contains my exception that the program would display to my user. 我如何确保如果用户输入的不是1或2,它将执行我的else命令,并在其中调用我的mainError()方法,该方法包含程序将显示给用户的异常。

The exception is raising because you don't have the options element you're trying to print in the message 出现异常是因为您没有要在消息中打印的options元素

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

Here you're trying to get options[a] or options [3], which doesn't exists. 在这里,您尝试获取不存在的选项[a]或选项[3]。 Put this print only inside the if/else that has a related option, and another print in the else without one. 将此打印仅放置在具有相关选项的if / else内,将另一张打印放入不包含相关选项的else /内。 Something like this: 像这样:

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("? "))

Well here you have to do some error-checking code like: 好了,在这里您必须执行一些错误检查代码,例如:

try:
    uchoice = int(input("? "))
except ValueError:
    <handling for when the user doesn't input an integer [0-9]+>

Then to handle the overflow when a user enters an index which isn't within the list's range: 然后在用户输入不在列表范围内的索引时处理溢出:

try:
    options[uchoice - 1]
except IndexError:
    <handling for when the user inputs out-of-range integer>

Of course this adds overhead due to the try: ... except <error>: ... statement so in the most optimal case you would use conditional checking per something like this: 当然,这会由于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.

相关问题 列表接受可迭代对象作为输入。 但是,当输入为int或float时,例如list(1),则不接受此输入。 为什么? - Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why? CSV模块读入文件,位于其他文件夹(例如,我的下载文件夹)中 - CSV Module Reading In Files, which are in some other folder (e.g. my Downloads folder) 使用python扩展时链接到其他库(例如boost) - Linking to other libraries (e.g. boost) when using python extensions 创建类的实例时如何限制可能的输入。 例如,仅创建类的整数实例 - How to restrict the possible inputs when creating an instance of a class. For e.g. only creating integer instances of a class python中any()函数的对立面是什么,例如没有任何 - What is the opposite of any() function in python, e.g. without any 声称使用点表示法(例如.sort())的Python方法在字符串以外的其他类型上不起作用吗? - Is the claim that Python methods that use dot notation e.g. `.sort()` don't work on types other than string true? 为什么当我尝试定义带注释的类型 class 成员(例如列表或字典)时 PyPy 失败? - Why PyPy fails when I try to define type annotated class member (e.g. list or dict)? 数字后面的包含点的数组(例如[1. 2.]与没有点的数组(例如[1 2])和有什么区别? - What is the difference between and array containing dot after the number e.g. [ 1. 2. ] and an array without dot e.g. [ 1 2 ]? 为什么分配给空列表(例如 [] = &quot;&quot;)不是错误? - Why isn't assigning to an empty list (e.g. [] = "") an error? 折叠 Numpy arrays 为标量,例如,乘以零 - Collapse Numpy arrays to scalar when, e.g., multiplying by zero
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM