2016-10-24 55 views
1

我有一個十進制到二進制轉換器,如下所示:在整數用戶輸入中打印消息而不是valuerror?

print ("Welcome to August's decimal to binary converter.") 
while True: 
    value = int(input("Please enter enter a positive integer to be converted to binary.")) 
    invertedbinary = [] 
    initialvalue = value 
    while value >= 1: 
     value = (value/2) 
     invertedbinary.append(value) 
     value = int(value) 
    for n,i in enumerate(invertedbinary): 
     if (round(i) == i): 
      invertedbinary[n]=0 
     else: 
      invertedbinary[n]=1 
    invertedbinary.reverse() 
    result = ''.join(str(e) for e in invertedbinary) 
    print ("Decimal Value:\t" , initialvalue) 
    print ("Binary Value:\t", result) 

用戶輸入立即聲明爲整數,所以數字以外的東西進入終止程序,並返回一個ValueError。我怎樣才能做到這一點,打印一條信息,而不是終止於ValueError的程序?

我嘗試採取從我的二進制將十進制轉換器的方法:

for i in value: 
     if not (i in "1234567890"): 

其中我很快意識到,不會因爲value工作是一個整數,而不是字符串。我一直在想,我可以將用戶輸入保留爲默認字符串,然後將其轉換爲int,但我覺得這是一種懶惰和粗暴的方式。

但是,我是否正確地認爲在用戶輸入行之後嘗試添加的任何內容都不起作用,因爲程序在它到達該行之前會終止?

其他建議?

回答

1

我相信什麼被認爲是最Python化方式在這些情況下是包裹行你就可能會在一個try/catch異常(或嘗試/除外),並顯示一個適當的消息,如果你得到一個ValueError例外:

print ("Welcome to August's decimal to binary converter.") 
while True: 
    try: 
     value = int(input("Please enter enter a positive integer to be converted to binary.")) 
    except ValueError: 
     print("Please, enter a valid number") 
     # Now here, you could do a sys.exit(1), or return... The way this code currently 
     # works is that it will continue asking the user for numbers 
     continue 

另一種選擇,你有(但比處理異常慢得多)的,而不是轉化爲int立刻,檢查輸入字符串是否是使用字符串的str.isdigit()方法和跳過數循環(使用continue語句)如果不是。

while True: 
    value = input("Please enter enter a positive integer to be converted to binary.") 
    if not value.isdigit(): 
     print("Please, enter a valid number") 
     continue 
    value = int(value) 
2

您需要使用try/except塊來處理ValueError異常。您的代碼應該是這樣的:

try: 
    value = int(input("Please enter enter a positive integer to be converted to binary.")) 
except ValueError: 
    print('Please enter a valid integer value') 
    continue # To skip the execution of further code within the `while` loop 

如果用戶輸入無法轉換爲int任何值,它會提高ValueError例外,這將是由except塊處理,將打印你所提到的消息。

閱讀Python: Errors and Exceptions瞭解詳細信息。按照該文檔中,try聲明的工作原理如下:

  • 首先,(在tryexcept關鍵字之間的聲明(S))的try條款執行。
  • 如果沒有發生異常,則跳過except子句並完成try語句的執行。
  • 如果在執行try子句期間發生異常,則會跳過該子句的其餘部分。然後,如果它的類型匹配以except關鍵字命名的異常,則會執行except子句,然後在try語句之後繼續執行。
  • 如果發生與except子句中指定的異常不匹配的異常,它將傳遞到外部try語句;如果沒有找到處理程序,則它是一個未處理的異常,並執行停止並顯示如上所示的消息。