Я использую 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'.Если вы не первый присваиваете 'count', то' count = count + 1' не имеет никакого смысла. – Shashank
Связано с http://stackoverflow.com/questions/19259837/i-cannot- print-the-final-value-of-a-variable/19259914 # 19259914 –