我的无限循环有什么不对?

011*_*100 0 python while-loop

这是我的代码:

#!/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)
Run Code Online (Sandbox Code Playgroud)

这是不完整的片段:

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)    
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这个循环继续循环.循环的条件是,当变量z的值小于长度的值时,继续循环.循环中的长度不会增加,我在循环中添加一行,每次迭代都会增加1到z.但是,由于某种原因,它继续无限循环.我不明白为什么?

DSM*_*DSM 6

看起来像是对我使用空格的不一致.尝试使用运行代码

python -tt your_program_name.py
Run Code Online (Sandbox Code Playgroud)

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

 "    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',
Run Code Online (Sandbox Code Playgroud)

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

始终使用四个空格标签:让生活变得更加轻松.大多数编辑器都可以配置为执行此操作.