Home > Enterprise >  Can anyone help me with understanding and using While Loop in list
Can anyone help me with understanding and using While Loop in list

Time:07-28

I have using while loop to input value in list, but every time the loops run, the value is replaced by a new value entered. I have pasted the code below, any help would be great

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

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

empty_word = False

while not empty_word:
  guess = input("Guess a letter: ").lower()
  for letter in chosen_word:
      if letter == guess:
          print("Right")
      else:
          print("Wrong")
  display = []
  for letter in chosen_word:
    if letter == guess:
      display.append(letter)
    else:
      display.append('_')
    
  print(display)

if "_" not in display:
  empty_word = True
  print("you win")

CodePudding user response:

Since you initialized the list in the loop, the list will be initialized every time the loop runs. If you want to append to the list without clearing it at every iteration, initialize it outside of the loop.

CodePudding user response:

2 things:

  1. You want to initialize display outside of your loop, otherwise you are creating an empty list at every iteration. This also means that you need to replace letters inside the list instead of appending to it, otherwise you will extend the list's length every time.
  2. Your last if block needs to be indented inside your loop, otherwise you are never setting empty_word to True and never exiting your loop.
  • Related