2015-04-19 25 views
-1

我想了解異常處理,並想給自己一些練習。下面是我的代碼,它讓用戶輸入一個分數,並將其打印回屏幕上。我的問題是,最終的返回語句沒有返回,所以我得到錯誤NoneType' object is not iterable。如果用戶不輸入分數,我如何處理這個異常?「NoneType」對象不可迭代「:我知道我的函數什麼也沒有返回,但

def printing_fractions(): 
    frac = str(input("Input a fraction then press enter: ")) 
    try: 
     n, d = frac.split('/') 
     int(n)/int(d) 
     return n,d 
    except ValueError: 
     print("You did not enter a fraction")  
    except ZeroDivisionError: 
     print("You cannot divide by zero") 
    return 

numerator, denominator = printing_fractions() 
print "Your fraction is: " + numerator + "/" + denominator 
+0

你想如何「處理」它?也就是說,你想在這種情況下做什麼? – BrenBarn

+0

我想打印「你輸入一個整數,請輸入一個分數」之類的東西 - 或者只是某種錯誤信息。 – ASm

+0

你已經這麼做了。 – BrenBarn

回答

1

你的問題是你從你的函數返回兩種不同的類型。在第一種情況:return n,d,並在第二:return None

然後,假設當你運行你會得到兩個值的函數:numerator, denominator = get_fraction()

這條線是哪裏出現了問題。如果您返回None,您目前已將其設置爲有效回報,則會中斷。

一種可能的方法來解決你的代碼:

def printing_fractions(): 
    ...  
    except ZeroDivisionError: 
     print("You cannot divide by zero") 
    return 0,0 

numerator, denominator = get_fraction() 
if denominator != 0: print "Your fraction is: " + numerator + "/" + denominator 

編輯:

只是想指出,通常當我趕上這樣的異常我只是用一個單一的情況除外:

def printing_fractions(): 
    frac = str(input("Input a fraction then press enter: ")) 
    try: 
     n, d = frac.split('/') 
     int(n)/int(d) 
     return n,d 
    except: 
     print("Please try entering your fraction properly")  
     printing_fractions() 

這將導致異常再次遞歸調用該函數,直到提供正確的輸入。

+2

[不要使用''except',永遠](https://docs.python.org/2/howto/doanddont.html#except),它比你討價還價得多! –

+0

@Ulrich Schwarz確實如此!在我發佈在這裏之前,我曾嘗試過,它讓我感到更多的情況超出了我的預期。 – ASm

+0

感謝您的提示。我想我會在未來除了例外以外! – MikeTGW

0

因爲您已經打印了一條錯誤消息,我假設您希望在出現錯誤時再次提示用戶輸入。

def printing_fractions(): 
    while True: 
     frac = str(input("Input a fraction then press enter: ")) 
     try: 
      n, d = frac.split('/') 
      int(n)/int(d) 
      return n,d 
     except ValueError: 
      print("You did not enter a fraction")  
     except ZeroDivisionError: 
      print("You cannot divide by zero") 

這樣,如果您發現異常,用戶將被提示再次輸入。這確保了你的函數總是返回一個有效的分數。

相關問題