我是Python的新手,正在学习“ For”循环。我想做的是使用for循环遍历我在变量中设置的一些字母,然后打印特定的字母以发出消息。
基本上我所做的每件事都遇到了多个错误,现在我只是在寻找一个正确方法的示例。
currentpos = 0
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for unenc in enc:
while True:
if unenc == unenckey[currentpos]:
currentpos = 0
print(unenc)
break
elif unenc == 'q':
print(' ')
break
else:
if currentpos == 11:
currentpos = 0
if currentpos != 11:
currentpos = currentpos + 1
continue
它一直持续下去,我不确定该怎么办。
答案 0 :(得分:0)
您只需要删除while
循环。您放置了while True
,这就是导致它永远持续下去的原因。更改为此:
currentpos = 0
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for unenc in enc:
if unenc == unenckey[currentpos]:
currentpos = 0
print(unenc)
break
elif unenc == 'q':
print(' ')
break
else:
if currentpos == 11:
currentpos = 0
if currentpos != 11:
currentpos = currentpos + 1
continue
答案 1 :(得分:0)
currentpos = 0
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for char in enc:
if char in unenckey:
print(char)
答案 2 :(得分:0)
您的内部循环卡在了找不到的字符上,因为您从未在到达currentpos == 11时使用过break
。您已经弄清楚了大部分逻辑。只需解决以下问题即可
currentpos = 0
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for unenc in enc:
while True:
if unenc == unenckey[currentpos]:
currentpos = 0
print(unenc)
break
elif unenc == 'q':
print(' ')
break
else:
if currentpos == 11:
currentpos = 0
break #modified
if currentpos != 11:
currentpos = currentpos + 1
continue
恐怕“ mamfia”并不能完全那样工作。唉。 :)
随着您对基本结构更加熟悉,可以在in
运算符中使用python的某些功能来直接检查unenkey中是否存在每个字母。
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for unenc in enc:
if unenc == 'q':
print(' ')
elif unenc in unenckey:
print(unenc)
else:
pass
答案 3 :(得分:0)
您是否要通过如下更新代码来确保while loop
总是break
?
currentpos = 0
unenckey = ['a', 'e', 'f', 'h', 'i', 'k', 'm', 'o', 'r', 's', 't', 'w']
enc = "ztxhcccczxbatnnsqhlllowqtdhdzxveqmvbanmfxzibbaqwojrdkls"
for unenc in enc:
#print(unenc)
while True:
if unenc == unenckey[currentpos]:
currentpos = 0
print(unenc)
break
elif unenc == 'q':
print(' ')
break
else:
if currentpos == 11:
currentpos = 0
if currentpos != 11:
currentpos = currentpos + 1
break #Make sure your while loop breaks!
问题的真相是实际上,如果我们总是以中断结尾,则不需要while循环。我只是把它留在那里,因为您已经表明这是出于教育目的。