2017-10-08 42 views
0

這是我的代碼。當用戶輸入除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()方法,該方法包含我的例外程序將顯示給我的用戶的異常。

回答

0

的異常升高,因爲你沒有你想的消息

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

我已經做了,但現在如果他們輸入一個號碼錯誤將只顯示給用戶大於2 –

+0

我該如何設置,以便在用戶輸入或@時顯示錯誤? –

+0

這個你需要用try/check來檢查你從用戶得到的值,或者你可以使用字符串作爲用戶輸入,並在輸入之後進行cast/validate以避免這種情況。 –

0
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

它工作成功!謝謝。 –

相關問題