这是我的代码:
#!/usr/bin/env python
encodec = {
'a':22 , 'b':24 , 'c':26 , 'd':28 , 'e':12 , 'f':14 , 'g': 16 , 'h':18 , 'i':32 , 'j':34 , 'k':36 , 'l':38 , 'm':42 , 'n':44 , 'o':46 , 'p':48 , 'q':50 , 'r':52 , 's':54 , 't':56 , 'u':58 , 'v': 62 , 'w':64 , 'x':66, 'y': 68 , 'z':72 , ' ':74 , '.':76 , ',':78 , "'":82 , '?':84 , '"':86
}
decodec = {
22:'a' , 24:'b' , 26:'c' , 28:'d' , 12:'e' , 14:'f' , 16:'g' , 18:'h' , 32:'i' , 34:'j' , 36:'k' , 38:'l' , 42:'m' , 44:'n' , 46:'o' , 48:'p' , 50:'q' , 52:'r' , 54:'s' , 56:'t' , 58:'u' , 62:'v' , 64:'w' , 66:'x', 68:'y' , 72:'z' , 74:' ' , 76:"." , 78:',' , 82:"'" , 84:'?' , 86:'"'
}
option = raw_input("Would you like to 'encode' or 'decode' a word? ")
while option.lower() not in ('encode' , 'decode'):
option = raw_input("Please enter a valid response ('encode' or 'decode'): ")
if option.lower() == 'encode':
word = raw_input("Enter a string to be encoded: ").lower()
length = len(word)
z = 1
result = []
while z < length+1:
a = word[z-1]
result += str(encodec[a])
z = z + 1
print int(''.join(result))
elif option.lower() == 'decode':
num = (raw_input("Enter your text to be decoded: "))
length = len(num)
z = 1
result = []
while z < length+1:
a = num[z-1:z+1]
result += str(decodec[int(a)])
z = z + 1
print ''.join(result)
这是不太有效的片段:
elif option.lower() == 'decode':
num = (raw_input("Enter your text to be decoded: "))
length = len(num)
z = 1
result = []
while z < length+1:
a = num[z-1:z+1]
result += str(decodec[int(a)])
z = z + 1
print ''.join(result)
我不明白为什么这个循环继续循环。循环的条件是当变量 z 的值小于长度的值时,继续循环。循环中的长度不会增加,我在循环中添加了一条线,每次迭代都会将 1 添加到 z 中。但是,出于某种原因,它继续无限循环。我不明白为什么?