Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用while循环而不是for循环_Python_Python 3.x - Fatal编程技术网

Python 使用while循环而不是for循环

Python 使用while循环而不是for循环,python,python-3.x,Python,Python 3.x,因此,代码的结果将如下所示 我的问题是如何通过使用while循环而不是For循环来获得相同的输出。我知道我必须使用索引来迭代每个字符,但当我尝试时失败了。有什么帮助吗 secret_word = "python" correct_word = "yo" count = 0 for i in secret_word: if i in correct_word: print(i,end=" ") else: print('_',end=" ") 计数时len(秘密字)

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

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

for i in secret_word:
 if i in correct_word:
      print(i,end=" ")
 else:
      print('_',end=" ")
计数时
len(秘密字):
如果在秘密中纠正了单词[count]:
打印(正确的单词,end=“”)
其他:
打印(“”,end=“”)
计数=计数+1
谢谢

您可以这样做:

while count < len(secret_word):
     if correct_word [count]in secret_word[count]:
          print(correct_word,end=" ")
     else:
          print("_",end=" ")
 count = count + 1
secret\u word=“python”
更正
计数=0
当计数
另一种使用
的方法是模拟第一个字符的弹出。当字符串的“真实性”变为false且没有更多字符要处理时,while循环终止:

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
或者,您可以实际使用带有LH pop的列表:

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

下面是一种简单的编写程序的方法,它使用
while
循环而不是
for
循环。在适当的时候,代码会从无限循环中中断

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

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

让我们看看您尝试但失败的代码。
count
没有正确缩进。您不需要在
secret\u word
中使用
count
,只要使用:
如果secret\u word中的单词[count]正确:
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()