Skip to content Skip to sidebar Skip to footer

Check For Repetition In Input (python)

How do i check for a repeating input(letter) for a hangman game? Example: word is apple input is Guess a letter: a output is Well Done! then guess next word input is Guess a letter

Solution 1:

You could store the inputs in a list, let's call it temp.

Then you could check to see if the input exists in the list when the user goes to input a new letter.

guess = input()
if guess in temp:
    print"You've already guessed {}".format(guess)
else:
    #do whatever you want

Solution 2:

Here's an easy way. Start by initializing a list:

guesses = []

Then in your loop:

letter = input("Guess a letter or enter '0' to guess the word: ")

if letter in guesses:
    print("Already guessed!")
    continue

guesses.append(letter)

Solution 3:

So you probably want to invert the order of your checks in your program so that you deal with the try again stuff first. Following that change, add another condition that determines if the letter matches those already guessed. This results in something like:

already_guessed = set()  # I made this a set to only keep unique valueswhile lives > 0and word: # I changed this to test > 0print(f"\nYou have {lives} guesses left") # I also added an f-string for print formatting
    letter = input("Guess a letter or enter '0' to guess the word: ")
    iflen(letter) > 1:
        print("You can only guess one letter at a time!")
        print("Try again!")
        continue# If you reach this point, start the loop again!elif letter in already_guessed:
        print("You already guessed that!")
        print("Try again")
        continueelif letter in num:
        print("You can only input letter a - z!")
        print("Try again!")
        continueelif letter.lower() in word:
        print("Well done!", letter, "is in my word!")
        lives -= 1else:  
        already_guessed.update(letter)
        # It wasn't a bad character, etc. and it wasn't in the word\# so add the good character not in the word to your already guessed # and go again!

You would need to add your other conditional branches, but this should get you there. Good luck.

Post a Comment for "Check For Repetition In Input (python)"