hameed
hameed

Reputation: 87

using a while loop instead of for loop

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

Upvotes: 2

Views: 1010

Answers (3)

Noctis Skytower
Noctis Skytower

Reputation: 22001

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.

Upvotes: 0

dawg
dawg

Reputation: 103834

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

Upvotes: 1

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

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

Upvotes: 3

Related Questions