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

so the outcome of the code will look like this _ y _ _ o _ my question is how i can i get the same output by using while loop instead of using For loop. i know i have to use index to iterate over each character but when i tried i failed . so any help?

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

Thanks

2
  • 3
    Let's see the code where you tried and failed. Commented Feb 5, 2016 at 17:49
  • You count not indented properly. You don't need count in secret_word just use: if correct_word[count] in secret_word: Commented Feb 5, 2016 at 17:54

3 Answers 3

3

You can do this:

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
Sign up to request clarification or add additional context in comments.

Comments

1

Another way to use while is to simulate a pop of the first character. The while loop terminates when the 'truthiness' of a string becomes false with no more characters to process:

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

Or, you can actually use a list with a 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=" ")

Comments

0

Here is a simple, way of writing your program with a while loop instead of a for loop. The code breaks out of an infinite loop when appropriate.

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()

It uses logic similar to how the for loop is implemented internally. Alternatively, the example could have used exception handling instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.