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

I need my display variable to be updated. Now it is resetting to null list

while test_list != display:
 display=[] 
 guess = input("Guess a letter: ").lower()
 for letter in chosen_word:
  
  if letter == guess:
      display+=[letter]  
  else:
      display+=["_"] 
 print(display)

Display variable is resetting to null 

This code is part of hangman game. So the letter inputted by the user is checked for match with the word and it prints out a list with underscores and along with the correct guess in each position.
However, when i input another word the display variable is resetting to null list. I want it to be updated by the code.

Thanks in Advance 🙂

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 :

that is because you are creating a new display list on every iteration of your loop without saving your old list somewhere.

a solution is to save your old list in a variable, let’s call it old_display, then we can check if that letter was already picked.

old_display = []
while test_list != display:
    display = []
    guess = input("Guess a letter: ").lower()
    for letter in chosen_word:

        if letter == guess:
            display += [letter]
        elif letter in old_display:  # check what was picked before
            display += [letter]
        else:
            display += ["_"]
    old_display = display  # update the old list to be the new list
    print(old_display)
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