为什么代码没有进入if语句?

时间:2018-01-23 20:49:15

标签: python debugging if-statement

在这段代码中,我想创建一个包含字符串加密版本的字典。但是,在第一个if语句中,代码似乎跳过了两个if语句而不理解为什么

8   import string
9   
10  
11  drunk="abcdefABC"
12  joe={}
13  shift=4
14  for i in drunk:
15      for j in string.ascii_lowercase:
16          listj=[]
17          listj.append(j)
18      for x in string.ascii_uppercase:
19          listx=[]
20          listx.append(x)
21      if i in listj:
22          tempvara=ord(i)
23          tempvarb=chr(tempvara+shift)
24          joe[i]=tempvarb
25      if i in listx:
26          vartempa=i.lower()
27          vartempb=ord(i)
28          vartempc=chr(vartempb+shift)
29          vartempc=vartempc.upper()
30          joe[i]=vartempc
31  print(Joe)

以Python编码

////

更新

import string


drunk="abcdefABC"
joe={}
shift=4

for j in string.ascii_lowercase:
    listj=[]
    listj.append(j)
for x in string.ascii_uppercase:
    listx=[]
    listx.append(x)
for i in drunk:

    if i in listj:
        tempvara=ord(i)
        tempvarb=chr(tempvara+shift)
        joe[i]=tempvarb
    if i in listx:
        vartempa=i.lower()
        vartempb=ord(i)
        vartempc=chr(vartempb+shift)
        vartempc=vartempc.upper()
        joe[i]=vartempc
print(Joe)

我注意到有人说我已将列表放在循环内部,所以我把它拿出来并在那里声明它但似乎它不起作用并且有同样的问题

1 个答案:

答案 0 :(得分:4)

您为每个字符初始化listjlistx,因此只有zZ才会进入该字符。

这意味着:对于a,您初始化listj,然后添加a。对于b,您再次初始化listj,放弃a。再次c ...

使用调试器,您可以轻松找到它: PyCharms debugger

如您所见,变量j已经在字符c,但列表listj已被清除。

不是在内部声明数组,而是在循环外移动:

import string
drunk="abcdefABC"
joe={}
shift=4

listj=[]
for j in string.ascii_lowercase:
    listj.append(j)

listx=[]
for x in string.ascii_uppercase:
    listx.append(x)

for i in drunk:
    if i in listj:
        tempvara=ord(i)
        tempvarb=chr(tempvara+shift)
        joe[i]=tempvarb
    if i in listx:
        vartempa=i.lower()
        vartempb=ord(i)
        vartempc=chr(vartempb+shift)
        vartempc=vartempc.upper()
        joe[i]=vartempc
print(joe)

并且,正如@Fred Larson所提到的,循环中列表的初始化是多余的。你也可以这样做

import string
drunk="abcdefABC"
joe={}
shift=4

listj=string.ascii_lowercase
listx=string.ascii_uppercase

for i in drunk:
    if i in listj:
        tempvara=ord(i)
        tempvarb=chr(tempvara+shift)
        joe[i]=tempvarb
    if i in listx:
        vartempa=i.lower()
        vartempb=ord(i)
        vartempc=chr(vartempb+shift)
        vartempc=vartempc.upper()
        joe[i]=vartempc
print(joe)

如果你摆脱了更多的源代码,你可能会发现你的代码有一个错误:

import string
drunk="abcdefABC"
joe={}
shift=4

for i in drunk:
    if i in string.ascii_lowercase:
        joe[i] = chr(ord(i) + shift)
    if i in string.ascii_uppercase:
        vartempa = i.lower()
        joe[i] = chr(ord(i) + shift).upper()
print(joe)

请注意,永远不会使用vartempa

相关问题