对于循环在一次迭代后结束

时间:2016-04-16 05:21:16

标签: python for-loop

所以我用这段原始代码替换了#34中的单词;填写空白"我正在参加一场蟒蛇课的比赛:

while victory == False:
    round0 = ''
    round1 = ''
    round2 = ''
    round3 = ''
    round4 = ''
    round5 = ''
    answerx = listchange()
    while round0 != answerx[0]:
        print ''.join(glvl)
        round0 = raw_input('What word is ___(0)___? ')
    while round1 != answerx[1]:
        print ''.join(num_replace(glvl,0))
        round1 = raw_input('What word is ___(1)___? ')
    while round2 != answerx[2]:
        print ''.join(num_replace(num_replace(glvl,0),1))
        round2 = raw_input('What word is ___(2)___? ')
    while round3 != answerx[3]:
        print ''.join(num_replace(num_replace(num_replace(glvl,0),1),2))
        round3 = raw_input('What word is ___(3)___ ')
    print ''.join(num_replace(num_replace(num_replace(num_replace(glvl,0),1),2),3))
    print 'Congratulations!'
    victory = True

它被拒绝了,因为它只适用于问题中的四个空白,无论有多少空白点,我的代码都应该有效。

所以现在我一直在努力改造它并且遇到了很多麻烦。这是迄今为止我最成功的尝试:

for i in glvl:
    glvlstr = ''.join(glvl)
    answerx = listchange()
    counter = 0
    if i == blank_list[counter]:
        print glvlstr
        askq = raw_input('What word is ' + i + '? ')
        if askq == answerx:
            glvl[i] = askq
            glvlstr = ''.join(glvl)
    counter += 1

它开始运行并运行:

Please select a difficulty level: easy, normal, hard, maximum-carnage, bonus-level: easy
In ___(0)___ if you want to pass the W3 ___(1)___ make sure you ___(2)___ your ___(3)___!
What word is ___(0)___? HTML

但那时它就退出了。然后打印出来:

In HTML if yuou want to pass the W3 ___(1)___ make sure you ___(2)___ your ___(3)___!
What word is ___(1)___? 

然后循环逐字逐句替换它们直到完成。

2 个答案:

答案 0 :(得分:0)

将counter设置为零,检查if语句,然后递增计数器。但是在下一次迭代中,您将计数器重置为零,因此if始终检查counter = 0.在for循环之前初始化计数器。似乎这可能是你的问题。

答案 1 :(得分:0)

当您为每次迭代递增counter时,您可以将它清理一下,如下所示

for counter,i in enumerate(glvl):
    # glvlstr = ''.join(glvl) unnecessary
    answerx = listchange() # what does this do?
    if i == blank_list[counter]:
        print ''.join(glvl)
        askq = raw_input('What word is ' + i + '? ')
        if askq == answerx:
            glvl[i] = askq
            # glvlstr = ''.join(glvl) unnecessary