简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM