Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loop goes on forever despite condition being met

My while loop is supposed to end once each letter in display is not an underscore.

However despite display updating to remove all underscores. The loop keeps going on, and I can’t figure out why.

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)


print(f'Pssst, the solution is {chosen_word}.')

display = []
for _ in range(word_length):
    display += "_"


guess = input("Guess a letter: ").lower()

def check_letter():
  for position in range(word_length):
      letter = chosen_word[position]
      if letter == guess:
          display[position] = letter
  print(display)

check_letter()

for item in display:
  while item == "_":
    guess = input("Guess a letter: ").lower()
    check_letter()

print("You've Won")
  

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

item is a copy of your display element. This may be what you want

for i in range(word_length):
  while display[i] == "_":
    guess = input("Guess a letter: ").lower()
    check_letter()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading