Okay, so I started playing with Python yesterday, and it's really cool.

I don't yet understand the variable scoping rules, but the problem I am
currently grappling with is 'initial values in functions'.

For example, I am writing a program to decode packets from an incoming
data stream, and I want a function that, once the packet has been
accumulated, verifies the packet's integrity by checking the CRC.  All
the bit/byte/packet handling is done and working, and the CRC code works.
All I want is a simple packet counter:

def handle_packet(new_packet, packet_counter=0, bad_CRC=0):
        
        packet_counter = packet_counter + 1

        if calc_CRC(new_packet) != 0:
                bad_CRC = bad_CRC + 1
                print "Bad CRC ",
        else:
                print "Good CRC",

        print bad_CRC, "/", packet_counter

The point here is that the function definition contains the initial
values for the number of packets (packet_counter) and the number of
bad CRCs seen (bad_CRC).  I expect the first call to initialise these
two variables to zero (once) and increment as appropriate in
subsequenct calls.  As I said, it all works, but for a sequence of 
good packets I get

Good CRC 0 / 1
Good CRC 0 / 1
Good CRC 0 / 1
...

Whereas I want

Good CRC 0 / 1
Good CRC 0 / 2
Good CRC 0 / 3
...

I am using as my reference

http://python.active-venture.com/tut/node6.html#SECTION006600000000000000000

Section 4.7.1, and I am running Python 2.4.1.

It seems to me I got all the hard bits working, and this should be trivial...

Thanks in advance,

Andy

Reply via email to