Make basic cipher function more readable
<p>I have this basic cipher function:</p>

<pre><code>def encrypt_decrypt(data, in_or_out):
    pass_lst = list(data)
    return_list = []

    if in_or_out == "in":
        for i in pass_lst:
            num = ord(i) + 10
            return_list.append(chr(num))
    else:
        for i in pass_lst:
            num = ord(i) - 10
            return_list.append(chr(num))

    return ''.join(return_list)
</code></pre>

<p>I want to make this cipher a little more readable and a little <code>DRY</code>er.. Is there a way I can shorten this function successfully?</p>

<p>You ca make it DRYer by computing the Â±10 from the <code>in_or_out</code> parameter. Eg,</p>

<pre><code>def encrypt_decrypt(data, in_or_out):
    delta = {'in': 10, 'out': -10}[in_or_out]
    return_list = []
    for i in list(data):
        num = ord(i) + delta
        return_list.append(chr(num))
    return ''.join(return_list)
</code></pre>

<p>And that can be made more compact by using a list comprehension:</p>

<pre><code>def encrypt_decrypt(data, in_or_out):
    delta = {'in': 10, 'out': -10}[in_or_out]
    return ''.join([chr(ord(i) + delta) for i in data])
</code></pre>

<p>Notice that I'm directly iterating over <code>data</code>. That will work if <code>data</code> is a string, list or tuple.</p>

<p>However, you should be aware that your code isn't safe: it doesn't handle char codes where <code>ord(i) + delta</code> is outside the 0-255 range.</p>

python python-2.7