2013-10-10 27 views
-1

我正在使用Python。我正在努力保持遞歸方法。當我使用count+=1時出現錯誤。這是爲什麼?我在使用sum=sum+count時也出現錯誤。這是錯誤:在遞歸方法中保持計數?

local variable 'count' referenced before assignment

這裏是我的代碼:

def receiveOnePing(mySocket, ID, timeout, destAddr): 
    #receives ping 
    timeLeft = timeout 
    while 1: 
     startedSelect = time.time() 
     whatReady = select.select([mySocket], [], [], timeLeft) 
     howLongInSelect = (time.time() - startedSelect) 
     if whatReady[0] == []: # Timeout 
      return "Request timed out." 
     timeReceived = time.time() 
     recPacket, addr = mySocket.recvfrom(1024) 
     header = recPacket[20:28] 
     type, code, checksum, id, sequence= struct.unpack("bbHHh", header)  
     if id ==ID: 
      sizeofdouble = struct.calcsize("d")#returns size of structure 
      timeSent = struct.unpack("d", recPacket[28 : 28+sizeofdouble])[0] 
      print "Type:%d Code:%d Checksum:0x%08x Packet ID:%d Sequence:%d RTT:%d ms % (type, code, checksum, id, sequence, rtt) 
      count+=1 
     timeLeft = timeLeft - howLongInSelect 
     if timeLeft <= 0: 
      return "Request timed out." 
     else : 
      return "REPLY from %s " % destAddr    
+0

格式代碼正確 –

+0

你需要'計數= 0'顯然,如果你不先賦值count,那麼'count = count + 1'沒有任何意義。 – Shashank

+0

相關http://stackoverflow.com/questions/19259837/i-cannot- print-the-final-value-of-variable/19259914#19259914 –

回答

2

您現在尚未分配的名稱計數的對象。您需要在引用它之前分配計數。試試:

count = 0 

在嘗試之前count += 1

+0

是的,我明白,但是當我把遞歸方法之外的count = 0時,它仍然給我那個錯誤 – user2847851

+0

,如果我把count = 0放在在方法中,計數保持爲1 – user2847851

+0

如果您的計數保持爲1,則ID可能不等於ID。 –

2

你沒結束就行打印「類型....您需要在此行結束引號的字符串。

0

添加count=0timeLeft = timeout