多個整數最近我發現測試的方法的變量是否是一個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的代碼審查部分這會更好嗎?
懶惰的答案:不要打擾測試。如果轉換爲int會導致未處理的崩潰,則用戶通過放入無意義的輸入來獲得他們應得的值。 – Kevin 2014-11-04 16:48:06
或者,[詢問用戶輸入,直到他們給出有效的響應](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response )可能對你有用。 – Kevin 2014-11-04 16:49:07
不夠公平=)但是有必要測試所有變量。 @凱文數據不是由人類輸入,而是由計算機輸入。然而,電腦有時決定不給我一個整數(我沒有訪問這臺電腦或它的代碼)。哦,誰下降了,請說明原因。我對這個網站比較陌生,只提問/回答了20個問題。 – 2014-11-04 16:49:09