2016-03-02 40 views
1

我有一個函數,可以計算出文件是否在n×n方陣中,即3x3或4x4。現在,如果我打電話的功能,它工作正常;它表示它是否是一個nxn正方形。嘗試/除功能是假的

我的問題是我想使用一個異常,如果該函數返回一個False值,那麼它將不會加載文本文件,但給出一個錯誤說,以確保該文件具有nxn網格。 因此,例如,如果我的網格存儲在一個文本文件中,我嘗試使用python代碼加載它;程序應該保持循環,直到文件格式正確。我不知道是否有布爾函數的異常

ABC 
DEF 
GHI 
J 

目前我有

def grid(n): 
    rows = len(n) 
    for row in n: 
     if len(row) != rows: 
      return False 

方式類似,文件打開工程;如果它不存在(FileNotFoundError),那麼它將保持循環,直到它找到輸入文件名

+0

每次發生異常時,都是因爲某些測試是False。你想要的可能是'ValueError',因爲你有正確的類型,但是錯誤的值。 – zondo

回答

1

下面是做到這一點的方法之一。如果square(d)返回False,只需提出適當的例外。

#Return True if sq is square, False otherwise 
def square(sq): 
    rows = len(sq) 
    return all(len(row) == rows for row in sq) 

def loaddata(): 
    while True: 
     try: 
      filename = input("Enter the name of the file to open: ") + ".txt" 
      with open(filename, "r") as f: 
       d = [] 
       for line in f: 
        splitLine = line.split() 
        d.append(splitLine) 

      if not square(d): 
       raise ValueError 

      break 

     except FileNotFoundError: 
      print("File name does not exist; please try again") 
     except ValueError: 
      print("The format is incorrect") 

    for line in d: 
     print("".join(line)) 

我們重置每次d[]通過的情況下,我們需要擺脫前一個文件不是方形的內容的循環。

+0

如果格式不正確,這將起作用。如果我在文本文件中將格式設置爲正確的nxn網格;它仍然表示格式不正確。任何理由?爲什麼你必須移動清單? – Xrin

+1

@Xrin對不起。我忘了發佈我的新版本的「方形」。給我一點時間。 –

+0

謝謝;實際上我原來的方形功能也適用;但由於某些原因,它只適用於我的文本文件在每個字母之間具有製表符間距的情況?真奇怪。如果我把它們放在一起,即ABC,那麼它不能正常工作。但它有很多方法 – Xrin

0

你很混淆處理異常(「except」語句)和引發異常。你應該在方做的是拋出一個異常而不是返回false,然後處理它在你的主程序:

def square(sq): 
    rows = len(sq) 
    for row in sq: 
     if len(row) != rows: 
      raise ValueError("the format is incorrect") 


def loaddata(): 
    while True: 
     try: 
      filename=input("Enter the name of the file to open: ") + ".txt" 
      with open(filename,"r") as f: 
       for line in f: 
        splitLine=line.split() 
        d.append(splitLine) 
       break 
      square(d) 

     except FileNotFoundError: 
      print("File name does not exist; please try again")  

     except ValueError: 
       print("The format is incorrect") 

    for line in d: 
     print("".join(line)) 
    return 
+0

如果這仍然不起作用(即仍然加載文件)這是否意味着代碼不正確或我的功能無法正常工作?因爲atm;它仍然沒有提高錯誤 – Xrin

+0

剛剛編輯的職位,實際上呼籲廣場。 – Chris