concatenation - Python False Concatenate Error? -
i can't seem find mistake. i'm trying write simple program encrypts messages using caesar shift method. however, i'm getting funky error. program follows:
alphabet = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25} alpha2 = dict (zip(alphabet.values(),alphabet.keys())) def key(n): code = alphabet in code: code[i] = (code[i] + n) % 26 in code: code[i] = alpha2[code[i]] return code def encode(x,n): my_key = key(n) message = [] in x: message.append(my_key[i]) print key(13) print encode("message",13)
i find absurd, because after running ./caesars.py
command line return
{'a': 'n', 'c': 'p', 'b': 'o', 'e': 'r', 'd': 'q', 'g': 't', 'f': 's', 'i': 'v', 'h': 'u', 'k': 'x', 'j': 'w', 'm': 'z', 'l': 'y', 'o': 'b', 'n': 'a', 'q': 'd', 'p': 'c', 's': 'f', 'r': 'e', 'u': 'h', 't': 'g', 'w': 'j', 'v': 'i', 'y': 'l', 'x': 'k', 'z': 'm'} traceback (most recent call last): file "./caesars.py", line 56, in <module> print encode("message",13) file "./caesars.py", line 27, in encode my_key = key(n) file "./caesars.py", line 15, in key code[i] = (code[i] + n) % 26 typeerror: cannot concatenate 'str' , 'int' objects
which means first run through of key
function successful, when encode
functions tries call key
function second time decides have issues? have printed types of n, , come out int. i'm sure oversight in code, life of me can't find it.
you expected
code = alphabet
to copy alphabet
dict code
. that's not happens. line evaluates alphabet
variable, producing reference dict, , makes code
refer same dict. setting items of code
change alphabet
, because both variables names same dict. in particular, after
for in code: code[i] = alpha2[code[i]]
all values of alphabet
strings.
if want copy, can make copy:
code = alphabet.copy()
though copy of alphabet
might not cleanest starting point construct code
.
Comments
Post a Comment