很难使用For循环

2024-09-30 01:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

它永远在继续,我不知道该怎么办。你知道吗


Tags: 消息forif错误字母例子正确处理print
3条回答

您的内部循环在找不到的字符上卡住了,因为您在到达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

不过,恐怕“妈咪”并不是这样的。唉。:)

随着对基本结构的熟悉,可以使用python在in操作符中的一些功能来检查unencey中是否直接存在每个字母。你知道吗

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
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)

您只需删除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

相关问题 更多 >

    热门问题