-1

我正在使用 Python。我正在尝试以递归方法计数。使用时出现错误count+=1。这是为什么?当我使用sum=sum+count. 这是错误:

赋值前引用的局部变量“count”

这是我的代码:

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             
4

3 回答 3

2

You have not yet assigned the name count to an object. You need to assign count before referencing it. Try:

count = 0

before you try count += 1.

于 2013-10-10T03:21:06.073 回答
2

您没有在 print "Type.... 行结束字符串。您需要在此行结束引号。

于 2013-10-10T03:22:57.917 回答
0

count=0之前添加timeLeft = timeout

于 2013-10-10T04:42:46.507 回答