使用while循环而不是for循环

时间:2016-02-05 17:48:47

标签: python python-3.x

secret_word = "python"
correct_word = "yo"
count = 0

for i in secret_word:
 if i in correct_word:
      print(i,end=" ")
 else:
      print('_',end=" ")

因此代码的结果将如下所示_ y _ _ o _ 我的问题是如何通过使用while循环而不是使用For循环来获得相同的输出。我知道我必须使用索引迭代每个字符,但当我尝试我失败了。那有什么帮助吗?

while count < len(secret_word):
     if correct_word [count]in secret_word[count]:
          print(correct_word,end=" ")
     else:
          print("_",end=" ")
 count = count + 1

由于

3 个答案:

答案 0 :(得分:3)

你可以这样做:

secret_word = "python"
correct_word = "yo"
count = 0

while count < len(secret_word):
    print(secret_word[count] if secret_word[count] in correct_word else '_', end=" ")
    count += 1

答案 1 :(得分:1)

使用while的另一种方法是模拟第一个字符的弹出窗口。 while循环终止于&#39;真实性&#39;字符串变为false,不再处理任何字符:

secret_word = "python"
correct_word = "yo"

while secret_word:
    ch=secret_word[0]
    secret_word=secret_word[1:]
    if ch in correct_word:
        print(ch,end=" ")
    else:
        print('_',end=" ")

或者,您实际上可以使用带有LH pop的列表:

secret_list=list(secret_word)
while secret_list:
    ch=secret_list.pop(0)
    if ch in correct_word:
        print(ch,end=" ")
    else:
        print('_',end=" ")

答案 2 :(得分:0)

这是一种使用while循环而不是for循环编写程序的简单方法。在适当的时候,代码会突然出现无限循环。

def main():
    secret_word = 'python'
    correct_word = 'yo'
    iterator = iter(secret_word)
    sentinel = object()
    while True:
        item = next(iterator, sentinel)
        if item is sentinel:
            break
        print(item if item in correct_word else '_', end=' ')

if __name__ == '__main__':
    main()

它使用的逻辑类似于内部实现for循环的方式。或者,该示例可能已使用异常处理。

相关问题