簡體   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