Debora Sanchez
Debora Sanchez

Reputation: 15

Why is python returning ValueError: list.remove(x): x not in list when the value is in the list?

I am making a Hangman game for practice. The game is set so that the computer randomly chooses a word from a list I have provided and returns the word in list form. A function then compares user input with the list and checks if user_input in list. If True, then it removes the input from the word to prevent the user to pass the same input more than once. That is where the error arises.

I know the letter is still in the list, so I can't understand why it says it's not. Here is the code:

import random

words = ["share","last","computer"]

def choose_word():
    choice = random.choice(words)
    return list(choice)
choice = choose_word()
original_word = choose_word()
choice == original_word

def get_input():
    return input("Choose a letter: ")


def check_input(user_input,choice):
    if user_input in choice:
        print("Correct.")
    else:
        print("Wrong.")
        return False

def list_to_string(l):
    string = ""
    return string.join(l)

tries = 0

while tries <= 6:
    choose_word()
    print(original_word) # This is for testing purposes.
    user_input = get_input() # To ensure the computer doesn't call a new random value.
    check = check_input(user_input,original_word)
    if check == False:
        tries += 1
    else:
        choice.remove(user_input) # To prevent the user from inputing the same value twice.
        if len(choice) == 0:
            print(f"You got it! The word is \'{list_to_string(original_word)}.\'")
            break

if tries == 6:
    print(f"Sorry, you are out of tries. The word was \'{list_to_string(original_word)}\'.")

Upvotes: 0

Views: 401

Answers (3)

McBrincie212
McBrincie212

Reputation: 1

There are a some problems with this code, like a ton. But i managed to fixed it for You, here! enjoy

import random


def main():
   words = ["share","last","computer"]
   choice_string = random.choice(words)  # Make a Random Choice on List
   word_choice_listed = list(choice_string)  # Make it as a List
   fails = 0

   def check_letter(word_choice_listed, letter, fails):
       if letter[0] not in word_choice_listed:
           print("Wrong Letter Given")
           fails += 1  # Increment Fails By One
           return fails, word_choice_listed, False  # Return is Very Necessary, Not Only to Give the 3 Values But To Break From Function
       print("Correct Letter Given")
       word_choice_listed.remove(letter)  # Remove the Letter
       return fails, word_choice_listed, True  # 3 Returned Values, Use Check If You want Or Remove It All By Together

   while fails <= 3:
       print(word_choice_listed)  # For Test purposes
       letter_input = input("Choose a letter: ")  # Get the Letter Input, And Only Select the First Character
       while len(letter_input) == 0:
            print("You Didn't Input a Letter, Please Try Again!")
            letter_input = input ( "Choose a letter: " )
       fails, word_choice_listed, check = check_letter(word_choice_listed, letter_input[0], fails)  # We Take 3 Variables as Returned Values
       if len(word_choice_listed) == 0:
           print(f"You Have Found The Word! {choice_string}")
           return
   print ( f"Sad You Didn't Found The Word, It Was {choice_string}!" )


# The If __name__ == "__main__ idiom
if __name__ == "__main__":
    main()

Upvotes: 0

OysterShucker
OysterShucker

Reputation: 5531

You could greatly reduce your issues by reducing the noise. Do each thing in order, and only as much as you need to do to fulfill that step. Wrapping functions in functions is complicating your problem space. By making it very simple, your issues become very simple ones.

import random

#game data
words  = ["share","last","computer"]
choice = original = random.choice(words)

#we can use a for loop to enforce tries
for _ in range(6):

    #this will run as long as the user keeps guessing correctly
    while (ch:=input("Choose a letter: ")) in choice:
    
        #remove guess letter
        choice = choice.replace(ch, '')
        
        #user won
        if not choice:
            print(f"You got it! The word is \'{original}\'.")
            break
            
        #user made a proper guess
        print('good guess')
         
    #if we got this far and there are still letters 
    #it must have been a bad guess    
    if choice: 
        print('try again')
        continue
    
    #the word must have been guessed to get this far
    #break the for loop    
    break
        
#lose message
if choice:
    print(f"Sorry, you are out of tries. The word was \'{original}\'.")

Upvotes: 1

user13963867
user13963867

Reputation:

Some problems here.

  • choose_word() at the beginning of the while loop does nothing: the assignment to choice inside this function modifies only a local variable, not the global environment.
  • you check_input on original_word, but remove from choice: it is going to fail randomly.
  • check_input returns nothing (i.e. None) when the element is found: while it's not what causes the bug, it's extremely poor design.

Upvotes: 1

Related Questions