2015-07-20 146 views
0

我有以下的代碼:如何確定原始輸入是一個整數還是不是在python中?

choice = raw_input("> ") 
    if "0" in choice or "1" in choice: 
     how_much = int(choice) 
    else: 
     dead("Man, learn to type a number.") 

好像if "0" in choice or "1" in choice被用來確定原始輸入的選擇是否是整數或沒有。爲什麼?我只是有點好奇。非常感謝您的時間和關注。

編輯。這似乎是一個類似的問題已經存在。見How to check if string input is a number?。非常感謝以下不同的答案。我很好奇的是:爲什麼我們可以使用如果選擇「0」或選擇「1」來確定原始輸入是否是python中的數字。

+2

看起來像是試圖檢查int()調用是否成功或產生錯誤。但是,它將無法捕獲像''0qwer''這樣的無效輸入。只需使用'try..except'構造就容易了。 – TigerhawkT3

回答

1
#!python 
try: 
    choice = raw_input("> ") 
except (EnvironmentError, EOFError), e: 
    pass # handle the env error, such as EOFError or whatever 
try: 
    how_much = int(choice) 
except ValueError, e: 
    dead("Man, learn to type a number.") 

它也可以這樣來包圍輸入和轉換過程在一個更復雜的try:塊:

#!python 
try: 
    choice = int(raw_input('> ')) 
except (ValueError, EOFError, EnvironmentError), e: 
    dead('Man, learn to type a number') 
    print >> sys.stderr, 'Error: %s' % e 

...這裏我也顯示出使用捕獲異常對象的一種方式以顯示與該異常相關的特定錯誤消息。 (也可以用更高級的方式使用這個對象......但是這對於簡單的錯誤處理就足夠了)。

0
choice = raw_input("> ") 
    if "0" in choice or "1" in choice: 
     how_much = int(choice) 
    else: 
     dead("Man, learn to type a number.") 

無法檢測到很多數字,如23

How do I check if a string is a number (float) in Python?可以幫到你。

+1

如果選擇'a0bc'會怎麼樣? – ozgur

+0

@ozgur [我如何檢查一個字符串是否是一個數字(浮點數)在Python?](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is- a-number-float-in-python)顯示了很多解決方案。 – letiantian

+1

但你的不是解決方案。 – ozgur

0

您可以使用isdigit()函數。

choice = raw_input("> ") 
if choice.isdigit(): 
    how_much = int(choice) 
else: 
    dead("Man, learn to type a number.") 
相關問題