karmesto karmesto - 1 year ago 79
Python Question

How to append even and odd chars python

I want to convert all the even letters using one function and all the odd numbers using another function. So, each letter represents 0-25 correspsonding with a-z, so a,c,e,g,i,k,m,o,q,s,u,w,y are even characters.

However, only my even letters are converting correctly.

def encrypt(plain):
charCount = 0
for ch in plain:
if charCount%2==0:
return ''.join(answer)

Answer Source

This are my two cents on that. What @mgilson is proposing also works of course but not in the way you specified (in the comments). Try to debug your code in your head after writing it.. Go through the for loop and perform 1-2 iterations to see whether the variables take the values you intended them to. charCount is never reassigned a value. It is always 0. And, yes charCount += 1 would make it change but not in the way you want it to..

def encrypt(plain):
    alphabet = 'abcdefghijklmnopqrwstuvwxyz'
    answer = ''
    for letter in plain:
            if alphabet.index(letter.lower()) % 2 == 0:
                answer += pycipher.Affine(7, 6).encipher(letter)
                answer += pycipher.Affine(3, 0).encipher(letter)
            answer += letter
    return answer

my_text = 'Your question was not very clear OP'
encripted_text = encrypt(my_text)

Also, i would not use ord(ch) because ord('a') = 97 and not 0 therefore odd instead of even.