使用while循环而不是for循环

2024-03-29 10:56:41 发布

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

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循环来获得相同的输出。我知道我必须使用索引来迭代每个字符,但当我尝试时,我失败了。有什么帮助吗?在

^{pr2}$

谢谢


Tags: 代码inforsecretifcount字符else
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

这里有一个简单的方法,用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循环在内部实现的逻辑。或者,该示例可以使用异常处理。在

另一种使用while的方法是模拟第一个字符的pop。当字符串的“truthiness”变为false且没有其他要处理的字符时,while循环终止:

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的列表:

^{pr2}$

相关问题 更多 >