0

这是我的代码:

#!/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 中。但是,出于某种原因,它继续无限循环。我不明白为什么?

4

2 回答 2

6

在我看来,空格的使用不一致。尝试使用运行您的代码

python -tt your_program_name.py

确认这一点。如果我查看您发布的原始代码,第一个片段如下所示:

 "    elif option.lower() == 'decode':\n",
 '    \tnum = (raw_input("Enter your text to be decoded: "))\n',
 '    \tlength = len(num)\n',
 '    \tz = 1\n',
 '    \tresult = []\n',
 '    \twhile z < length+1:\n',
 '    \t\ta = num[z-1:z+1]\n',
 '    \t\tresult += str(decodec[int(a)])\n',
 '        \tz = z + 1\n',
 "        print ''.join(result)\n",
 '    \t\n',

你可以看到z = z + 1线条的奇怪缩进。特别是,虽然您似乎使用制表符进行缩进,但该行只有一个制表符,所以即使它看起来在屏幕上正确缩进,我认为它实际上并没有被执行,因为它实际上不在while循环内.

始终使用四格制表符:让生活更轻松。大多数编辑器都可以配置为执行此操作。

于 2013-01-01T15:06:39.257 回答
1

这些代码在你那正常吗?

elif option.lower() == 'decode':
    num = (raw_input("Enter your text to be decoded: "))
    result = ''
    index = 0
    while index < len(num) -1:
        result += decodec[int(num[index:index +2])]
        index += 2
    print result

如果我将输入设置为222426,则输出为abc

于 2013-01-01T15:00:16.930 回答