2016-02-05 43 views
2
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循環,而不是爲循環

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

感謝

+3

讓我們看看您嘗試失敗的代碼。 – Kevin

+0

你'count'沒有正確縮進。 'secret_word'中不需要'count'只是使用:'如果secret_word中的correct_word [count]:' –

回答

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

使用while另一種方式是模擬的第一個字符的流行。當一個字符串的「感實性」爲假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流行:

secret_list=list(secret_word) 
while secret_list: 
    ch=secret_list.pop(0) 
    if ch in correct_word: 
     print(ch,end=" ") 
    else: 
     print('_',end=" ") 
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循環如何在內部實現。或者,該示例可以使用異常處理。