1

I've been trying to remaster my hangman game, but i ran into the problem

here's the problem

['p', 'l', 'a', 'n', 't', 's']
['*', '*', '*', '*', '*', '*']
Input ur guess : l
['*', 'l', '*', '*', '*', '*']
Input ur guess : t
['l', '*', '*', '*', 't', '*']
Input ur guess : 

the first line of code is for easier viewing of my program

the problem is that the .remove command removes the right element the first time, but not the 2nd time

i think theres a problem with the for loop colliding with the def() creating different x's, hence the different values

here's the code

import random
words=["random","trees","plants"]

def gen_word():
    global censored_word
    picked_word=random.choice(words)
    word=list(picked_word)
    censored_word =["*"]*len(picked_word)
    print(word)
    print(censored_word)
    input_func(word)
    
def input_func(word):
    global censored_word
    user_word=input("Input ur guess : ")
    if len(user_word) > 1:
        print("Ur input length is too long")
        input_func()
        return
    for x in range(len(word)):
        if user_word == word[x]:
            censored_word.remove(censored_word[x])
            censored_word.insert(x,user_word)
            print(censored_word)
        else:
            continue
    
    input_func(word)
    return
    

gen_word()
  • 8
    Don't remove and insert. If you want to change the nth item of the list, just do `my_list[n] = my_new_value`. – Thierry Lathuille Jul 19 '21 at 08:56
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Tomerikoo Jul 19 '21 at 09:02
  • 1
    Unrelated to your specific question, but also problematic: 1) Try inputting more than one letter, it will raise an error when you call `input_func()`. 2) You're recursively calling `input_func` at every input. Eventually, you'll hit max recursion (granted, probably not in any of your tests, but since you're learning to program you might as well learn itright from the beginning ;) ). Consider reworking that in a loop instead. – GPhilo Jul 19 '21 at 09:05
  • @GPhilo What if i just remove the `word` from the function and just `global word`, it would work right? – captainchungus Jul 20 '21 at 03:55
  • @Gphilo I also realised i forgot to add `word` inside `input_func`, that also solves the problem. Thanks so much! – captainchungus Jul 20 '21 at 04:13

0 Answers0