2012-04-20 103 views
13

IndentationError:意外unindent爲什麼?IndentationError:意外unindent爲什麼?

#!/usr/bin/python 
import sys 
class Seq: 
    def __init__(self, id, adnseq, colen): 
     self.id  = id 
     self.dna = adnseq 
     self.cdnlen = colen 
     self.prot = "" 
    def __str__(self): 
     return ">%s\n%s\n" % (self.id, self.prot) 
    def translate(self, transtable): 
     self.prot = "" 
     for i in range(0,len(self.dna),self.cdnlen): 
      codon = self.dna[i:i+self.cdnlen] 
      aa = transtable[codon] 
      self.prot += aa 
    def parseCommandOptions(cmdargs): 
     tfname = cmdargs[1] 
     sfname = cmdargs[2] 
     return (tfname, sfname) 
    def readTTable(fname): 
     try: 
      ttable = {} 
      cdnlen = -1 
      tfile = open(fname, "r") 
      for line in tfile: 
       linearr = line.split() 
       codon = linearr[0] 
       cdnlen = len(codon) 
       aa  = linearr[1] 
       ttable[codon] = aa 
      tfile.close() 
      return (ttable, cdnlen) 
    def translateSData(sfname, cdnlen, ttable): 
     try: 
      sequences = [] 
      seqf = open(seq_fname, "r") 
      line = seqf.readline() 
      while line: 
       if line[0] == ">": 
        id = line[1:len(line)].strip() 
        seq = "" 
        line = seqf.readline() 
        while line and line[0] != '>': 
         seq += line.strip() 
         line = seqf.readline() 
        sequence = Seq(id, seq, cdnlen) 
        sequence.translate(ttable) 
        sequences.append(sequence) 
      seqf.close() 
      return sequences  
    if __name__ == "__main__": 
     (trans_table_fname, seq_fname) = parseCommandOptions(sys.argv) 
     (transtable, colen) = readTTable(trans_table_fname) 
     seqs = translateSData(seq_fname, colen, transtable) 
     for s in seqs: 
      print s 

它說:

def translateSeqData(sfname, cdnlen, ttable): 
^
IndentationError: unexpected unindent 

爲什麼?我檢查了數千次,我找不到問題。我只使用Tabs,沒有空格。另外,有時它會要求定義這個類。這可以嗎?

+0

類中的所有方法/函數也需要'self'作爲它們的第一個參數,除非您使用了'staticmethod'或'classmethod'裝飾器。 – agf 2012-04-20 03:10:56

回答

43

這是因爲你有:

def readTTable(fname): 
    try: 

沒有try:塊之後匹配的except塊。每個try必須至少有一個匹配的except

請參閱Python教程的Errors and Exceptions部分。

+0

當然,呃​​! – John 2012-04-20 03:21:56

+0

你怎麼知道的,甚至沒有看到這個測試語句?! – Pacane 2012-08-10 16:07:23

+0

@Pacane如果你點擊「編輯Apr 20 at 22:56」,你可以看到編輯歷史。原始版本有更多的代碼。 – agf 2012-08-10 17:50:26

1

您沒有完成您的try聲明。你也需要和except在那裏。

0

該錯誤實際上可能出現在報告錯誤的代碼之前。例如,如果您的語法錯誤如下所示,您將收到縮進錯誤。語法錯誤實際上是在「except」旁邊,因爲它後面應該包含一個「:」。

try: 
    #do something 
except 
    print 'error/exception' 


def printError(e): 
    print e 

如果您將「except」改爲「except:」,錯誤將消失。

祝你好運。

+0

嗨。如果您在編輯之前查看我的答案以及問題的原始版本,則可以看到這已被涵蓋。此外,您需要將代碼縮進四個空格(或使用編輯框頂部的代碼按鈕)才能正確格式化。 – agf 2012-08-10 17:49:27