我正在使用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
答案 0 :(得分:2)
您尚未将名称计数分配给对象。您需要在引用计数之前指定计数。尝试:
count = 0
在尝试count += 1
之前。
答案 1 :(得分:2)
你没有在行打印上结束字符串“Type ....你需要在这一行上有一个结束引号。
答案 2 :(得分:0)
在count=0
timeLeft = timeout