2014-11-04 48 views
0

多個整數最近我發現測試的方法的變量是否是一個int或沒有在Python 3。它的語法是這樣的:檢查在Python 3

try: 
    a = int(a) 
except ValueError: 
    print("Watch out! The Index is not a number :o (this probably won't break much in this version, might in later ones though!") 
    error = True 

然而,測試多個變量,它的時候很快變得慘不忍睹:

def IntegerChecker(a, b, c, d): #A is Index, B is End Time, C is Distance, D is Speed Limit 
    global error 
    try: 
     a = int(a) 
    except ValueError: 
     print("Watch out! The Index is not a number :o (this probably won't break much in this version, might in later ones though!") 
     error = True 
    try: 
     b = int(b) 
    except ValueError: 
     print("Watch out! The End Time is not a number :o") 
     error = True 
    try: 
     c = int(c) 
    except ValueError: 
     print("Watch out! The Distance is not a number :o") 
     error = True 
    try: 
     d = int(d) 
    except ValueError: 
     print("Watch out! The Speed Limit is not a number :o") 
     error = True 

請問有沒有測試一個變量是否爲整數或不是一個更簡單的方法,如果不是,那麼一個變量更改爲true並打印唯一的消息給用戶?

請注意,我是一個Python新手程序員,但如果有一個更復雜的方法來做到這一點,我很想知道這個簡潔。另一方面,在Stack Exchange的代碼審查部分這會更好嗎?

+0

懶惰的答案:不要打擾測試。如果轉換爲int會導致未處理的崩潰,則用戶通過放入無意義的輸入來獲得他們應得的值。 – Kevin 2014-11-04 16:48:06

+0

或者,[詢問用戶輸入,直到他們給出有效的響應](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response )可能對你有用。 – Kevin 2014-11-04 16:49:07

+0

不夠公平=)但是有必要測試所有變量。 @凱文數據不是由人類輸入,而是由計算機輸入。然而,電腦有時決定不給我一個整數(我沒有訪問這臺電腦或它的代碼)。哦,誰下降了,請說明原因。我對這個網站比較陌生,只提問/回答了20個問題。 – 2014-11-04 16:49:09

回答

1

這是我的解決方案

def IntegerChecker(**kwargs): #A is Index, B is End Time, C is Distance, D is Speed Limit 
    error = False 
    err = { 
     'index': ('Watch out! The Index is not a number :o (this probably ' 
        'won\'t break much in this version, might in later ones though!'), 
     'end_time': 'Watch out! The End Time is not a number :o', 
     'distance': 'Watch out! The Distance is not a number :o', 
     'speed': 'Watch out! The Speed Limit is not a number :o' 
    } 
    for key, value in kwargs.items(): 
     try: 
      int(value) 
     except ValueError: 
      print(err.get(key)) 
      error = True 
    return error 

IntegerChecker(index=a, end_time=b, distance=c, speed=d) 
+0

謝謝你,完美的工作=)將在4分鐘內被接受。 – 2014-11-04 16:56:12

+1

爲什麼不只是使用b c和d作爲鍵? – 2014-11-04 16:56:38

+0

@PadraicCunningham這將更合乎邏輯,但是這使得它必須更易於閱讀。 – 2014-11-04 16:58:28

1

你並不需要爲每個變量單獨try-except塊。您可以在一箇中檢查所有變量,並且如果有任何變量是非數字的,則將引發exception,並拋出error

def IntegerChecker(a, b, c, d): #A is Index, B is End Time, C is Distance, D is Speed Limit 
    global error 
    try: 
     a = int(a) 
     b = int(b) 
     c = int(c) 
     d = int(d) 
    except ValueError: 
     print("Watch out! The Index is not a number :o (this probably won't break much in this version, might in later ones though!") 
     error = True 
+0

恐怕這個答案不會工作,因爲我需要每個失敗的唯一錯誤消息。 – 2014-11-04 17:12:36