Chr() arg not in range python
Question: I have been creating a program, and part of it involves modifying a list of
characters at random:

    
    
        while rel>0:
            pos = random.randint(0,len(out)-1)
            change = random.randint(-1*rel,rel)
            if (change+ord(out[pos]))>=255:
                change = 255-ord(out[pos])
            elif ((ord(out[pos]))-change)<=0:
                change = -1*(ord(out[pos]))
            out[pos] = chr(ord(out[pos])+change)
            rel -= abs(change)
    

Here, rel is the 'currency' the program is using to modify the list of
characters out. It first chooses a random position in the list, and a random
amount of change for that position between -rel and +rel, then changes the
value of that character using chr(ord(out[pos])+change). This was giving me
the error that this new modified value for the character was out of the
range(256), so I added the 2 if statements to be executed before changing the
character, however it still occasionally returns this error, especially for
large values of rel. How can I stop this?


Answer: The problem is in your choice of translation checks.

    
    
    elif ((ord(out[pos]))-change)<=0:
    

Why is this difference meaningful? All of the other operations are on the
_sum_ of the char and change. You get the error when **change <
-ord(out[pos])**: neither the **if** nor the **elif** condition is True, so
you wind up taking the **chr** of a negative number.

Change that minus to a plus, and you should be fine, until you get values of
rel beyond 512. If this is possible, please consider using modulus (%) instead
of a simple subtraction.

It took me a couple of minutes to trace this. I cleaned up the program and
added a pair of tracing **print** s to find out what's going on.

    
    
    import random
    out = list("Now is the time for all good parties")
    rel = 500
    
    while rel > 0:
        pos = random.randint(0, len(out)-1)
        chord = ord(out[pos])
        change = random.randint(-rel, rel)
        print "A", chord, change
        if change + chord >= 255:
            change = 255 - chord
        elif chord + change <= 0:
            change = -chord
        print "B", chord, change
        out[pos] = chr(chord + change)
        rel -= abs(change)
    
    print ''.join(out)
    

