2016-11-24 97 views
0
IDnum = input("\nprompt: ") 

if int(IDnum) >= 0 : 
    if int(IDnum) in T.keys() : 
     print("ID number(s) that {} will contact is(are) {}.".format(int(IDnum),T[int(IDnum)])) 
    else : 
     print("Entered ID number {} does not exist.".format(int(IDnum))) 
else: 
    break 

它實際上是一個while循環,接收ID號並檢查數字是否在文件中。使用if語句檢查輸入是否int> = 0

我想使它識別輸入是否爲整數> = 0,如果是別的,(例如,空格,回車,字符,浮點等)打破循環。

如何使用if語句執行此操作?

我已經試過 如果IDNUM == '' 或IDNUM == '' 或INT(IDNUM)< 0: 但如你所知,它不能涵蓋所有的其他情形。

+2

我會簡單地用'input_string.strip去()ISDIGIT()'檢查一個正整數。 –

+0

@SvenMarnach但是,這將意味着通過數字字符串兩次,一次用於驗證,另一次用於轉換 – comiventor

+0

@comiventor我認爲這是最可讀和最簡單的代碼。性能在這裏根本不重要(並且注意拋出異常很慢)。 –

回答

0
T = {1: 1, 2: 2} 
while True: 
    IDnum = input("\nprompt: ") 
    try: 
     num = int(IDnum) 
     if num < 0: 
      raise ValueError('Negative Integers not allowed') 
    except ValueError: # parsing a non-integer will result in exception 
     print("{} is not a valid positive integer.".format(IDnum)) 
     break 

    if num in T: 
     print("ID number(s) that {} will contact is(are) {}.".format(num,T[num])) 
    else: 
     print("Entered ID number {} does not exist.".format(num)) 

感謝@adirio和@ moses-koledoye的建議改進。

+0

建議將大部分代碼從try子句中取出並使用else子句,以避免在內部if中的ValueError失敗。 – Adirio

+0

@Adirio還有一個額外的東西,如果你的建議沒有。我試圖改善它,但不知道爲什麼只是完全刪除信貸給你:( – comiventor

+1

其他很好,它屬於try else else else語句,尋找這種類型的語句 – Adirio

0

使用try-except語句進行檢查。

def is_pos_int(IDnum): 
    ''' Check if string contains non-negative integer ''' 
    try: 
     number = int(IDnum) 
    except ValueError: 
     return False 
    if number >= 0: 
     return True 
    else: 
     return False 

例如

is_pos_int('1 ') # notice the space 

Out[12]: True 

is_pos_int('-1') 

Out[13]: False 

is_pos_int('1.0') 

Out[15]: False 

is_pos_int('word') 

Out[16]: False 

然後:

while True: 
    if not is_pos_int(IDnum): 
     break 
    else: 
     val = int(IDnum) 
     if val in T.keys() : 
      print("ID number(s) that {} will contact is(are) {}.".format(val, T[val])) 
     else : 
      print("Entered ID number {} does not exist.".format(val))